Fly3D

Fly3D SDK

http://www.fly3d.com.br

Demos Walkthrough

Guide

Reference

Tutorials


Fly3D Demos Walkthrough

Fly3D SDK

Demos Walkthrough

Home

Fly3D Quick Features List:

- BSP/PVS render
- Lightmap for static geometry (bsp and static objects)
- Diffuse and Specular hardware vertex lighting for dynamic objects
- Volumetric fog with fog maps
- Detail Textures
- Multitexture support (up to 4 texture units)
- Collision detection
- Dynamic lights
- Dynamic lightmap shadows
- Dynamic stencil shadows
- Physically based simulations (pos,vel,force,gravity,friction,bump,...)
- Animated meshes
- Triangle Strips and Fans
- 3D sound support
- Bezier surfaces (loft and extrude) and Bezier patches
- Cartoon like rendering with dynamic lighting
- Subdivision surfaces
- Particle systems
- Support for TGA and JPG textures
- Complete plug-in directed (make games and game objects by writing plug-ins)

Follow this walkthrough for a full demo of all features included in the Fly3D engine.
It will move you around all demo levels and give you clues on where to look and what to do.

While in the game you can always use the following keys to switch some render states:

F3 - Mute sound
F4 - Wireframe on/off
F5 - Fog on/off
F6 - Node only (draw single bsp node)
F7 - PVS on/off
F8 - Texture filtering on/off
F9 - Multitexture of/off
F10 - Map mode
F11 - Mipmapping on/off
F12 - Clear background on/off

The MENU level:

This is a level that implements a menu.
It will be the main interface for changing levels and starting multiplayer servers.
Pressing F1 while in any other level will load the menu.
Use Up and Down keys to select the desired menu item and Enter to activate it.

Things to notice while in this level:

- The arches are ducted solids made with Bezier curves in the loft plug-in.
- They have light maps and can change geometry detail while maintaining the lighting detail.
- Select options from the main menu group and change the detail settings by selecting the LOW,MEDIUM and HIGH options.
- Note that the surface subdivision is adaptative and areas with higher curvature gets more polygons.
- The menu item plug-in object execute console commads to implement its functionality.
- Press ESC for opening/closing the console (all menu selections will be printed there).

The CAR level:

This is a level implementing a simple car race. Select the S.PLAY menu option and then CAR for loading the level.
Use Up arrow to move the car forward and Left and Right arrows to turn.
There is another computer controled cars running around the track. Follow him the best you can. To add more cars to the race, type the following comand on the console:

activate car1

The scene is render as cartoon (bsp and dynamic objects) and for changing the number of color levels used in the bsp and cars, type the following command on the console:

set cartoonpicbsp gradient8.tga
set cartoonpic gradient3.tga

Turn on antialiasing with the following console command:

set antialias 1
set cartoonwidth 1.5

To add turn stencil shadows on (only for cards with stencil buffer support lilke the TNT, TNT2 and GeForce256), execute the following console command line:

set stencil 1

Some cards require the desktop windows mode to be at 32 bits/pixel in order to use hardware stencil buffers. If it gets too slow when stencil shadows are on, try switching to a 32 bit/pixel mode and re-run the level.

The WALK level:

This is a level implementing a walking first person shooter.
Press F1 to return to the menu.
Select S.PLAY and then WALK.

Things to notice while in this level:

- Use the mouse and the S and X keys to move around.
- Use the left mouse button to shoot something in the scene.
- Go to the yellow signs in the floor to jump around.
- Press F9 to turn multitexture off and see the detail textures (will be slow on some machines).
- Use the right mouse button to zoom in and see the detail textures applied to all scene geometry.
- Press F9 again to turn multitexture on if framerate is not good because of detail textures.
- Press W to turn on/off the head lights (dynamic spot with light maps).
- Several parts of the scene are Bezier surfaces (the arch, the top platform and some corners of the scene).
- Use the following console command for changing the surface detail:

set curveerr 1

and see the real round surfaces.

The SHIP level:

This is a level implementing a Descent like game (6 DOF ship inside a maze).

Things to notice while in this level:

- Turn the head light by pressing the W key
- Use the mouse and S,X,Q,E,A,D keys to move around
- Use the right mouse button to kill the enemies
- You can change the selected weapon using keys 1 to 6
- On the first room you will find a turret. Destroy it!
- Press the C key to turn the back camera on/off
- Run to the rooms, destroy the enemies and take all the itens

The BOX level:

This is another level implementing a walking first person shooter.
Load it with the following command line:

map box/box.fly

Or use the F1 menu shortcut and select S.PLAY then BOX.
Move around just like the previous walking demos (S,X,Q,E,arrows,mouse,SPACE)

Things to notice while in this level:

- On the center room, notice the dynamic shadow at the fan light.
- On the same room, notice the cartoon like objects. Use the headlight (W key) to illuminate them and notice that the scene lights dynamiclay illuminate them like cartoons.
- Use the left mouse button to fire missiles (kill yourself by shooting near to yourself and see the gibs and blood implemented with hitmarks).
- The two other rooms include fog maps.
- One is a red sphere fog. move inside it and see how fog maps makes a better fog than vertex fog with no geometry tessellation.
- The other fog is a box fog. Enter it and move around to see how the fog changes. Jump out of the fog with the boxes.
- This room also includes a ship/stone statue. They are subdivision surfaces. Change detail with the following command line:

set subdiv1.nsubdiv 0 no detail on stone (just a pyramid)
set subdiv1.nsubdiv 2 some detail
set subdiv1.nsubdiv 4 lot of detail
set subdiv2.nsubdiv 0 no detail on ship
set subdiv2.nsubdiv 1 some detail
set subdiv2.nsubdiv 2 lot of detail

- The dynamic objects are illuminated with hardware vertex lights. Notice the ship/stone, red on one side and blue on the other.
- Use the following command line to turn on/off the hardware lights:

set hwlights 0 turn on
set hwlights 1 turn off

- On a multiplayer game, the player model is also illuminated this way making a nice looking effect as the player moves near game lights.
- Fire a missile and notice the ship/stone also gets illuminated by the dynamic missile light.

The BOX level in multiplayer:

Create a multiplayer server for the box level using the main menu:

- Press F1 for loading the menu.
- Select M.PLAY (multi player) and then the BOX level.
- A server will start up. If all TCP/IP configurations are OK the server will show its network address.
- Join a game using CTRL-J (or select the join menu option)
- Type the player name and click search.
- If a game is found, select it and click the join button.
- In another computer in the network, open the frontend and join the game as above. (if you just have one computer you can run the server and two clients on the same machine)
- Place one player behind the fan.
- Use the other player to see the diffuse/specular player illumination (notice that the fan also casts shadows over the player).
- You can create other multiplayer games for the other demos just using the menu.


Fly3D Guide

Fly3D SDK

Guide

Home

Introduction to C++

classes
constructors
destructors
inheritance
virtual functions
operators
templates
public/private/protected

C++ in games

Engine Design and Architecture

Fly3D Software Architecture

Plug-ins
bsp_object virtual functions
Fly3D Front-ends
Collision Detection
Stock and Active object list
Sphere of Influence
Communicating between objects and plug-ins
Camera and Scene Drawing
Text Output
Rendering API

Introduction to C++

This is a brief introduction to C++ intended for those who already possess a good facility with C. Its emphasis is on those aspects of C++ that are useful in games. We start with definitions of new features that are included in C++ then move on to games applications
C has been the programming language used in games for a long time and most games are still written in C because of its speed and portability. With the advent of standard C++ definitions, C++ now possesses all the speed and portability of pure C in addition to those features that can be used to advantage game programming. Thus it is becoming the de facto standard for modern games.
The conventional wisdom is that C++ is slower than C but this will only occur if sufficient care is not taken in the coding.
Those C++ definitions that are useful in game are as follows:

classes

C++ classes are basically C structures with embedded code as member functions. Using classes to specify program objects, enables all the code that deals with the object to be included within it. This is a more organized approach and makes the object blocks easier to manage and re-use.
An example of the conversion of C to C++ representation is:

C

struct vector
{
float x,y,z;
};
void normalize(struct vector &v)
{
float len=sqrt(v.x*v.x + v.y*v.y + v.z*v.z);
if (len>0)
{ v.x/=len; v.y/=len; v.z/=len; }
}

C++

class vector
{
public:
float x,y,z;
void normalize();
};
void vector::normalize()
{
float len=sqrt(x*x + y*y + z*z);
if (len>0)
{ x/=len; y/=len; z/=len; }
}

constructors

A constructor is a method called when an instance of the class is allocated. Usually, members are initialized in the constructor. The constructor method must have the same name as the class it is from. The class may have more then one constructor if each of them have different parameters.
Examples of some constructors for the above vector class are:

class vector
{
public:
float x,y,z;

vector()
{ ; }; // uninitialised

vector(float f1,float f2,float f3)
{ x=f1; y=f2; z=f3; }; // initialised by 3 floats

vector(float f)
{ x=y=z=f; }; // initialised by 1 float

vector(vector &v)
{ *this=v; }; // initialised by another vector
};

...

{
vector v1;
vector v2(0.0f);
vector v3(0.0f,0.0f,1.0f);
vector v4(v2);
}

destructors

The destructor is a method called when the class is to be released. Usually, you must check for any data that was allocated by the object, and free it. The destructor is called when the class variable is deleted or gets out of scope. The destructor has the same name as the class, but with a '~' char at the beginning.

class A
{
public:
char *data;

A() { data=0; }
~A() { if (data) delete data; };

void allocate_data(int i)
{
if (data) delete data;
data=new char[i];
};
};

inheritance

Inheritance is the most important feature of C++ and is the ability t0 create a new class by derivation from one or more already existing classes. All properties and methods of the original classes are maintained and new properties and methods can be included. In this way you can create a base object and use this base code to create new objects that include the base object as a part of it.
For example, a plane can be defined as deriving from a vector (the plane normal) by adding a single float, the plane distance to the origin. This would be:

class plane : public vector
{
public:
float d;
float distance_to(vector &p);
};
float plane::distance_to(vector &p)
{
// return the distance from point p to the plane
return x*p.x + y*p.y + z*p.z - d;
}

virtual functions

A virtual function is a member function that you expect to be redefined in derived classes. If you define a function in a class as virtual, any class deriving from it, may have a new implementation for the function. When calling the virtual function from a class pointer (even from a base class pointer) the function that will be executed is the one defined at the allocation time. If your class do not implement the function, the base class version will be used.

class A
{
A() { printf("A constructor");
virtual ~A() { printf("A destructor");

virtual void print() { printf("A print"); };
};
class B : public A
{
B() { printf("B constructor");
virtual ~B() { printf("B destructor");
};
class C : public A
{
C() { printf("C constructor");
virtual ~C() { printf("C destructor");

virtual void print() { printf("C print"); };
};

...

{
A *a;
B b;
C c;
a=&b;
a->print();
a=&c;
a->print();
}

will print out:

A constructor
B constructor
A constructor
C constructor
A print
C print
C destructor
A destructor
B destructor
A destructor

operators

When a new class is defined operators must also be defined in order to be used. For example, consider the definition of the operator for the vector class defined above:

inline vector operator +(vector &v1,vector2 &v2)
{
vector v;
v.x = v1.x + v2.x;
v.y = v1.y + v2.y;
v.z = v1.z + v2.z;
return v;
}

inline operator *=(vector &v1,float f)
{
v1.x *= f;
v1.y *= f;
v1.z *= f;
}

This would be used in the following context

{
vector v1,v2(2,2,2),v3(3,3,3);
float f=0.2f;

v1=v2+v3;
v1*=f;
}

and will set v1 to (1,1,1)
The operators that can be redefined in this way are:

+ - ++ -- * / %
^ & | ~ ! < >
= += -= *= /= %= ^=
&= |= << >> >>= <<= ==
!= <= >= && || ->* ->
, () [] new delete new[] delete[]

Care must be taken when using operators like:

+, -, *, /, %, |, &, ^, and ~

as they return values. If the data being operated on is large (a 4x4 matrix, for example), the operators will execute slowly as new copies of temporary data will be created in the process. The following code shows this inefficiency problem.

class A
{
public:
int value;
A(int i=0)
{
value=i;
printf("constructor %i",i);
};
};
A operator +(A a1,A a2)
{
return A(a1.value+a2.value);
}

...

{
A a1(3)
A a2(4);
A a3=a1+a2;
}

will print out:

constructor 3
constructor 4
constructor 0
constructor 7

The output ‘0’ is the temporary class allocated by the operator that produces the inefficiency - this will be large for large objects.

templates

Templates are mechanisms for generating functions and classes based on type parameters (templates are sometimes called “parameterized types”). By using templates, you can design a single class that operates on data of many types, instead of having to create a separate class for each type.For example, to create a type-safe function that returns the minimum of two parameters without using templates, you would have to write a set of overloaded functions as:

// minimum for ints
int min( int a, int b )
return ( a < b ) ? a : b;

// minimum for longs
long min( long a, long b )
return ( a < b ) ? a : b;

// minimum for chars
char min( char a, char b )
return ( a < b ) ? a : b;

//etc...

By using templates, you can reduce this duplication to a single function template:

template <class T> T min( T a, T b )
return ( a < b ) ? a : b;

Templates can significantly reduce source code size and increase code flexibility without reducing type safety.

public/private/protected

This facility must be used wisely. Consider the following code:

class Point3D
{
public:
float& GetX() { return x; }
const float& GetX() const { return x; }
float& GetY() { return y; }
const float& GetY() const { return y; }
float& GetZ() { return z; }
const float& GetZ() const { return z; }

private:
float x, y, z;
};

Making accessors for a basic structure like this provides no benefit. Making the accessors inline will make their use as fast as direct access. But then the class would have to be used as follows:

Point3D p1, p2;
float dist = sqrt(
p1.GetX()*p2.GetX() +
p1.GetY()*p2.GetY() +
p1.GetZ()*p2.GetZ());

instead of:

float dist = sqrt(p1.x*p2.x + p1.y*p2.y + p1.z*p2.z);

The only time protected data should be used is when is when you don’t want the users of the class to either know about the data or modify the data directly.

C++ in games

Engine Design and Architecture

The purpose of these notes is to describe the main design choices that were made in the implementation and the reasons for them.
Engine architecture design factors are motivated by many requirements. The predominant ones are efficiency of image generation, quality of image generation and the provision of a development platform.
The example engine is based on BSP technology. Although BSP management was originally developed for first person shooter games it is a general and versatile scene management methodology and will admit many applications as the examples will demonstrate. Different applications will use different partitioning methods to build the BSP object and these options are embedded in the plug-in that converts the model into the tree.
The implemented applications are examples of common games genres and include:
1st person shooter game (ship and walking person)
car racing and pursuit game
three-dimensional strategy game
BSP technology is also versatile enough to facilitate combinations of the scene types that support these games. These are:

  • Closed environments - BSP planes are made coincident with the faces and every BSP partition is categorized as in or out.
  • Landscapes - partition planes are normal to the ground plane and BSP partitions contain groups of faces
    3D strategy games partitions - this is an extension of the previous and includes a 3rd partition plane orientation which defines BSP partitions to be rectangular solids which contain games objects for selection etc.
  • combinations - it is possible to implement environments which will contain combinations of these scene types. A type separating plane dichotomizes the different scene within a single tree.
    A common example might be the traversal from a landscape into a closed environment or vice versa. In this case the two types of environment are merged into a single BSP tree by having, as the root node, the plane that separates the environments. The tree is then built by applying the different building utilities to each side of the tree.

The applicability of BSP technology depends, of course, on the nature of the game application. A popular genre - football games - may or may not be beneficially implemented as a BSP tree depending on the relative complexity of the landscape v. the players. If the stadium is complex then the landscape approach can be used. If, however, the complexity of the 22 players - dynamic objects - is much greater than the landscape then BSP technology will not be optimal.

In general BSP technology is best in applications with large complex static meshes and its inherent advantages reduce as the number and complexity of the dynamic objects increases. It is also supreme in applications which require collision detection with the static mesh.

Game development is facilitated by building the environment or level using a modeling utility or editor then writing plug-ins to define different behaviors, both visual and dynamic for the game objects. Ideally new plug-ins should be developed to create a unique game but several sample plug-ins are given which can be edited (source code) or have their behavior altered by changing the parameter values.
The normal advantages of plug-in pertain. The front-end has no knowledge of the nature of the plug-ins and is not re-compiled when new plug-ins are added. It sees the plug-ins as a group of BSP objects which are new classes, defined by the user, and derived from the BSP base class.
Dynamic objects are handled with their reference position defaulting to particle behavior.

Fly3D Software Architecture

The design reflects the motivation of ease of game development in two main ways. First all behaviors are embedded in plug-ins. This means that the engine and front-ends are separate and distinct from the game application. The engine becomes a tool used by the game developer who needs to know little about the detailed engine behavior (precise ways in which scene management or collision detection, for example, is implemented).

Second inheritance in C++ is heavily exploited. The engine only knows about bsp_objects and many new classes can easily be created in a plug-in that inherits the bsp_object properties and behaviors. Many different objects, that share a common behavior, can be implemented as a base object which specifies the behavior once only.
The flyEngine is a .lib file that needs to be to be linked with all front-ends, plug-ins and utilities. It includes a global pointer where all access to the engine should be directed:

flyEngine *flyengine;

The classes defined in the Fly3D.dll file are:

class vector; // standard x,y,z 3D vector
class mat4x4; // 4x4 matrix to represent rotations, translations and scales
class boundbox; // axis aligned bounding box
class plane; // 3D plane
class vertex; // 3D vertex
class face; // 3D face
class local_system; // local system defined by 3 axis perpendicular vectors
class base_object; // the base class for all objects to derive from
class sound; // raw sound data
class mesh; // 3D mesh with faces, vertices ...
class anim_mesh; // animated 3D mesh with 3D vertex morphing
class stripfan_mesh; // mesh specified as strips and fans
class bezier_curve; // Bezier curve with any dimension
class bezier_patch; // Bezier surface made of several patches
class particle; // point particle in 3D space
class bsp_node; // node from the bsp tree
class bsp_object; // object inside one bsp node (all plug-ins derive from this class)
class static_mesh; // object containing faces in a leaf bsp node (derived from bsp_object)
class light_map; // bitmap for caching light
class light_map_pic; // collection of bitmaps for caching light
class light_vertex; // dynamic vertex light info
class class_desc; // describe fly plug-in classes
class flydll; // handles one dll plug-in
class flydllgroup; // group of fly plug-ins
class directX; // DirectX wrapper
class picture; // a 24 or 32 bits/pixel bitmap
class console; // console with text input and command interpreter
class flyEngine; // the main interface

The engine class includes all the scene objects, textures, models, sounds and curves. It is the main interface with several functions which interact with the simulation data.
One fly level or scene(.fly files) is composed of the following items all included in the flyEngine class:
a BSP tree (BSP nodes, faces, vertices) representing the static scene or level

// vertex array for static bsp faces
int nvert;
vector *vert;

// faces array for static bsp
int nfaces;
face *faces;

// the bsp tree
bsp_node *bsp;

an array of pictures to be used as texture maps

int npiclib;
picture *piclib[MAX_PICTURES];

object meshes, sounds and curves stored as linked lists

// linked list of model objects
mesh *model_obj0;

// linked list of sound objects
sound *sound_obj0;

// linked list of curve objects
bezier_curve *bezier_curve0;

the group of plug-ins used

// group of active plug-ins
flydllgroup dll;

a linked list of stock bsp objects. These are objects that can be cloned and activated during the execution of the game. Activation means adding the object to the BSP tree and to the list of active objects.

// linked list of stock script objects
bsp_object *stock_obj0;

a linked list of active bsp objects.

// linked list of active objects
bsp_object *active_obj0;

Plug-ins

The Fly3D plug-ins are dll files that defines new classes derived from the engine bsp_object class. In this way we can create a dll that implements a new bsp_object to be used in the simulation. The new object will be able to give new behaviour to new virtual functions defined by the bsp_obejct that requires different behavior. Common re-implemented functions are the draw, step and ray_intersect virtual functions.

The bsp_object class is derived from a particle, and so it behaves as a particle. It includes several properties that are common to all plug-ins like position, vel, force, mass, bump, friction and radius. If no custom behavior is defined in new implementations for the object virtual step function, it will move and collide as a particle, using its current vel and force parameters.

The following plug-ins are supplied:

gamelib.dll

  • sound - implements 3D sound
  • particle_system - particle emitter and population
  • sphere - procedural strip fan sphere object
  • shadow - simple texture mapped shadow
  • explode - a group of other objects (particle system, sound, sphere, lights etc.). when an explosion occurs all the objects are activated at once

lights.dll

  • light - a dynamic light source
  • spotlight - a dynamic spotlight
  • spritelight - implements haloes and billboard type lighting
  • meshlight - a 3D object that implements a non-point source - a light object with shape and extent.

bezobj.dll

  • bezier_extrude - an extruded Bezier curve object
  • bezier_loft - a lofted Bezier curve object

volfog.dll

  • fogsphere - a spherical fog volume
  • fogbox - a box fog volume

panorama.dll

  • panorama - implements a texture mapped panorama-box created from 6 images

viewport.dll

  • viewport - implements a camera position and a viewport

subdivsurf.dll

  • subdivsurf - a mesh that subdivides creating better looking models

cartoon.dll

  • cartoon_mesh - a mesh object that render like cartoons

weapon.dll

gun can include any of the other objects in the dll. It is a container for the projectiles and includes parameters for different behaviour

  • hit_mark - paints marks due to an explosion onto objects
  • mine - implements a static object which is triggered by nearby objects
  • laser - billboard based projectile that simulates a laser gun
  • missile - mesh projectile that travels until it collides when it then explodes

menu.dll

  • menu_group - a group of menu items
  • menu_item - selectable menu item
  • menu_camera - camera that can be set to view the group and select menu items

ship.dll

  • ship - a mesh object that behaves as a flying spaceship
  • turret - implements a static gun with azimuth and elevation control
  • robot - ship enemy that attempts to track and destroy
  • power_up - a resource of special abilities collected by the player (visibility, missiles etc.)
  • container - mesh that enables a power-up after being destroyed
  • door - mesh that is animated on contact

walk.dll

  • person - person mesh
  • elevator - elevator which activates on contact
  • jump_pad - pad that applies forces to any player moving on top of it

car.dll

  • camera - implements a camera that can be targeted to any car. The targeted car
    is under user control and the camera also gathers user input for this car.
  • car - car

One Fly3D plug-in can implement any number of bsp_objects derived classes. Each class can include any number of custom properties. The properties can be of predefined types like int, float, vector, color, string, picture, mesh, sound, curve, pointer to another stock or active bsp_object etc.

Plug-ins may draw, enumerate objects or do both. The set of draw plug-ins effectively draw into depth-ordered layers which are composited into the frame buffer. In the above exam0ple the first - panorama.dll - draws the backgrounds and enumerates no objects. The object, however, is not inserted into the BSP tree (because it is the background. Gamelib.dll draws nothing but enumerates several objects (light, sound, etc.). The third plug-in draws the rendered view from the player and implements the player object. The final one enumerates an object and draws it as a two-dimensional object directly onto the screen. This object is not inserted into the BSP tree.

The advantage of this organization is the ability to easily define (and clone game) objects by defining their update and draw functions. From the rendering point of view it effectively combines a BSP rendering strategy with a layered approach. The plug-ins are associated with the layers which can be blended into the frame buffer using different blend modes.

As an example of a game action element consider the plug-in dependency for the following case. We require a missile that has sound fixed to it, whose exhaust paints light on nearby objects as it travels and explodes using a particle explosion also with the appropriate sound. The missile is also to emit smoke. The light plug-in instance used by the missile causes the light map(s) within the sphere of influence of the missile light to be recomputed. Sound is fixed to the missile and travels with it. Smoke is modeled and emitted by the travelling missile by simulation in a particle system. The missile ‘carries’ the explosion and when it is destroyed, this explosion is cloned into the missile position in the BSP tree - effectively replacing it. The activation of the explosion may itself use sound instances and an animated mesh.

bsp_object virtual functions

The bsp_object class defines several virtual functions that should be re-implemented in order to define your own behaviors. If these are not implemented then the object will behave as a particle.

virtual void init();

This function is called for all objects after scene loading is completed. At this point you should initialize all data that your object requires.

virtual int step(int dt);

dt is the elapsed time from the last frame and your object should be updated using this time.
If the object has moved in this time you must return true. Returning 0 will not reposition the object in the BSP tree.

virtual bsp_object *clone();

The clone function must return a new instance of the object with the same parameter settings as the original. It is used to duplicate objects.

virtual mesh *get_mesh();

If the object has a mesh representation then this function should return its current mesh object. If a mesh is returned by this function then drawing, ray intersection and collision will be handled internally.

virtual void draw();

You must draw the object mesh representation and this function is called by the BSP draw for all objects within the view frustum and which have not been culled by the PVS. If not implemented a get_mesh will be called and if it returns a mesh that mesh will be drawn, otherwise no drawing will take place for this object.

virtual mesh *ray_intersect(vector& ro,vector& rd,vector& ip,float& dist,int &facenum,float rad=0.0f);

For special objects that require special ray intersection routines. If not implemented a get_mesh will be called and if it returns a mesh the ray intersection will be done with the mesh. Otherwise no collision detection will occur.

virtual int get_custom_param_desc(int i,param_desc *pd);

Here you should return the description of all external parameters that your object implements.

virtual int message(vector& p,float rad,int msg,int param,void *data);

This is a general object message procedure. Here you should process all messages directed to the object; for example, dynamic illumination or any other custom game message.

Fly3D Front-ends

Front-ends are applications created using the flyengine lib that open a scene and loop through the simulation. The fly.exe, flyEditor.exe, fly.ocx and fluserv.exe are all examples of Fly3D front-ends. They are responsible for creating and initializing a render if needed (the server front-end is an example of a frontend without a render) and loading the plug-ins

The main loop in a front-end is as follows:

// compute elapsed time since last frame in ms (dt)
T1=current time
dt=T1-T0
if dt < 10 return
T0=T1
if dt>1000 return
// simulate dt ms
call flyengine->step(dt)

dt is the time interval for the next frame and in the step function, the following order of operations are performed:

 // get input state (keyboard and mouse)
directx->get_input();

// restores all light maps changed in last frame
for each active object
if object life is < 0
destroy object removing it from BSP tree and active
  object list
elsecall object->step(dt)
if this returns true reposition object in BSP tree as it may have changed nodes

// update all light maps that were changed in this frame (this operation, of
  course, is
// necessary only for hardware assisted rendering because the maps have been
  cached into the
// hardware

// send a message to all the plug-ins informing them of the sumulation step

dll.send_message(FLYM_UPDATESCENE,dt,0);

// if in multiplayer mode, process all multiplayer messages

// messages like connect/disconnect and server quit are processed by the engine
  and

// custom multiplayer messages are passed on to the plug-ins

check_multiplayer();

If we are in server mode, no render is defined so no input and light map operations will be executed.
It is apparent in the above that there is no reference to any rendering activity. BSP rendering occurs when the plug-ins process the update scene message. Some may effect a render and others may not. For example weapon.dll effects no render. Ship.dll on the other hand effects a (BSP) render of the entire scene using the current ship position as the camera position. Another example is viewport.dll which can implement, for example, a back facing camera or a missile camera. This selects a small viewpoint, sets the camera to the required position and effects a BSP render.

Collision Detection

The following functions from the flyEngine should be used for collision detection:

int collision_bsp(bsp_node *n,vector& p1,vector& p2,int elemtype=0,float rad=0.0f);
int collision_test(bsp_node *n,vector& p1,vector& p2,int elemtype=0,float rad=0.0f);

The collision_test returns 0 if no collision is found between p1 and p2 and 1 if a collision is found (not the closest collision). The collision_bsp returns the closest collision from p1 to p2.

If the elem type is specified, only objects with the specified type will be intersected (-1 for only the BSP faces). If radius is >0, the collision will be tested for a sphere with the specified radius.

The distinction of usage between a nearest collision and the detection of any collision is as follows. A moving object always needs the nearest collision for correct impact calculation. On the other hand a robot tracking a player simply needs to know if the player is still visible from his viewpoint in which case an ‘any’ collision will suffice.Information about the collision is returned in the flyEngine class members:

// ray intersection data
bsp_object *hitobj; // bsp_object intersected
mesh *hitmesh; // mesh from the bsp_objects intersected
int hitface; // face from mesh intersected
vector hitip; // intersection point in global co-ordinates

Stock and Active object list

All objects defined in a .fly file are loaded into the stock objects linked list when a open_fly_file command is executed. When saving a .fly file, all object properties in the stock objects the liked list are saved to the file.

Any stock object can be activated (cloned and added to the bsp) using the following command from the flyEngine class:

void activate(bsp_object *stockobj,int flag=1);

This will make a clone of the stock object (using the clone() bsp_object virtual function) and add it to the end of the active object linked list. If flag is true, the object is also added to the bsp.
All objects in the active object linked list will have its step() function called for every frame and may be selected for drawing if in the current view frustum and not culled by the pvs.

Sphere of Influence

Spheres of influence are used for many operation in the engine. It allows fast selection of all objects in a sphere positioned anywhere in the bsp. A callback function is used, and a call is made for each bsp_object included inside the specified sphere of influence.

// recourse bsp calling a custom calback function
void apply_bsp(bsp_node *n,vector& p,float rad,void *data,void (*func)(void *data,bsp_object *e));

The callback function should be something like this:

void apply_bsp_callback(void *data,bsp_object *e)
{
// ...
}

Communicating between objects and plug-ins

Plug-ins are groups of objects and there are 2 types of messages used for communication between them - object messages and plug-in messages. Object messages are processed in the message() bsp_object virtual function. Plug-in messages are processed in the dll exported fly_message() function.
The following functions are used for sending messages:

 void flyEngine::send_bsp_message(bsp_node *n,vector& p,float
  rad,int msg,int param,void *data);
int flydll::send_message(int msg,int param,void *data);

The send_message() function sends the message to all plug-in dll in the current scene calling the fly_message() exported function of all dlls. The send_bsp_message() send a message to all bsp_object derived classes included in the specified sphere of influence.

Camera and Scene Drawing

Each plug-in dll will receive a FLYM_UPDATESCENE message every frame. At this point it might draw over the frame buffer if needed. Usually, one plug-in will draw the scene from the players perspective, but other plug-ins like the viewport may also draw the scene from other objects perspectives for implementing missile cameras, and rear cameras. The code will be:

flyengine->set_camera(camobj);
flyengine->draw_bsp();

Text Output

The following functions are used for text output. When entering text mode, a 2D mode is selected for the render. This way we can use 2D calls to draw text textured faces to represent the letters.

// text output functions
void start_text_mode(); // sets 2D mode
void end_text_mode(); // ends 2D mode
void draw_text(int x,int y,char *text); // draw text
void draw_text_center(int x,int y,char *text); // draw centered text
void set_status_msg(char *fmt, ...); // outputs to console

Drawing the status of a game, for example, would be as follows:

flyengine->start_text_mode();

char str[64];
sprintf(str,"FPS:%i N:%i", flyengine->frame_rate,flyengine->nodedrawcount);
flyengine->draw_text( 0,0, str );

flyengine->end_text_mode();

Rendering API

The source code has been written using both OpenGL. All rendering is done inside the object draw() virtual function as already explained. New objects created on plug-ins should implement the bsp_object function draw(). In it you must place the appropriate calls required for drawing your object. A simple example for drawing a mesh inside a newly created object would be:

void my_object::draw()
{
// Draw with OpenGL

glPushMatrix();
glTranslatef(pos.x,pos.y,pos.z);

glBlendFunc(GL_ONE, GL_ONE);
my_mesh->draw();
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

glPopMatrix();
}

A detailed treatment of programming in OpenGL is outside the scope of this text. A summary of each set of operations in the code above is:

Setting the current rendering matrix to position the object in global co-ordinates

glPushMatrix();
glTranslatef(pos.x,pos.y,pos.z);

Set the blending mode required for this object:

glBlendFunc(GL_ONE, GL_ONE);

Draw the object mesh

my_mesh->draw();

Restore the blending mode

glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

Restore rendering matrix

glPopMatrix();


Fly3D Tutorials

Fly3D SDK

Tutorials

Home

Tutorial 1

How to build a level model

Tutorial 2

More complex level modelling

Tutorial 3

Creating the level .BSP file

Tutorial 4

Creating the level script .FLY file

Tutorial 5

Creating the level light map .LMP file

Tutorial 6

Creating the level .PVS file

Tutorial 7

Adding Fly3D plug-ins

Tutorial 8

How to model a dynamic object

Tutorial 9

Creating a new Fly3D plug-in

Tutorial 10

Adding a new object to a Fly3D plug-in

Tutorial 11

Creating a player object (observer)

Tutorial 12

Creating a front-end


Fly3D Tutorial 1 - How to build a level model

Fly3D SDK

Tutorials

Home

Tutorial 1

How to build a level model

· Introduction

This tutorial describes how to build a level using 3D Studio Max and export it, using the supplied BSP export plug-in. If you have not got access to 3D Studio Max you can go direct to tutorial 3 and use the supplied BSP files.

At the end of the operations exemplified in this tutorial, we have constructed the geometry of a level (stored as a .max file).

· 3D Studio Max operations

1) Draw a plan view of the level using the line tool. The plan of the model must consist of a closed polygon.

2) Use the extrude modifier to convert the plan into a 3d model.

3) Invert the face normals using the edit mesh modifier. This is done by selecting the face mode in the edit mesh modifier, selecting all faces from the model with a selection window and then clicking the invert normal button from the edit mesh modifier. This is an import step, and converts the model from a normal 3d graphics object, with outwards facing normals, to an interior.

4) Create the texture co-ordinates using the UVW Map modifier and select box mapping. Set the length, width and height to apropriate values for your level.

5) Define the required materials using the standard material with bitmap diffuse mapping and apply it to the model. You can also apply different materials to different parts of the model.

6) Create some light objects (you can use simple small box objects for example). Place the lights in appropriate positions and apply a standard material with self illumination value larger then 0.

7) Associate real dimensions to your model by setting the desired values in the Preferences menu on the general tab system unit scale. For example, for a wall of 50 units length, you might set 0.2 unit = 1 meter, making the virtual wall 10 meters long.


Fly3D Tutorial 2 - More complex level modelling

Fly3D SDK

Tutorials

Home

Tutorial 2

More complex level modelling

· Introduction

This tutorial details a simple methodology for building a closed environment level.

At the end of the operations exemplified in this tutorial, we have constructed the geometry of a level (stored as a .max file).

The basic building block is a box. The level is constructed by joining boxes together, dragging vertices to convert the boxes into truncated rectangular pyramids then deleting shared faces to create the final environment. An advantage of this construction method is that correct topology is maintained for the environment. This means that if a construction, such as that shown in last figure from this tutorial is required, then the face normals will have the correct direction (the direction of the surface normals must be consistent with the rule that the entire environment must exhibit a single inside space and a single outside space). This rule is more difficult to guarantee as more complex shapes are used by an editor.

· 3D Studio Max operations

1) Draw 7 boxes as shown using the box creation tool

2) Use the edit mesh modifier to move the vertices of boxes 2 and 6 as shown so that they align with the vertices from boxes 1 and 7

3) Attach all boxes to each other using the attach multiple tool to create a single environment. All boxes now merge to form a single object

4) Use the edit modifier again to remove the 6 pairs of shared faces (note there are 2 triangles per face)

5) Still using the edit mesh modifier, select all vertices and weld them with the weld vertices tool deleting duplicated vertices (vertices that share the same position in space).

6) Still using the edit mesh modifier select all face and invert their normals so that they point inwards.

7) Apply material and texture mapping co-ordinates using the material editor and UVW mapping tool.

8) Create some light objects (you can use simple small box objects for example). Place the lights in appropriate positions and apply a standard material with self illumination value larger then 0.

9) Associate real dimensions to your model by setting the desired values in the Preferences menu on the general tab system unit scale. For example, for a wall of 50 units length, you might set 0.2 unit = 1 meter, making the virtual wall 10 meters long.


Fly3D Tutorial 3 - Creating the level .BSP file

Fly3D SDK

Tutorials

Home

Tutorial 3

Creating the level .BSP file

· Introduction

This tutorial explains how to export any 3D Studio Max scene into a Fly3D bsp file.

At the end of this tutorial you will have constructed a bsp tree to partition the space of the model, constructed a text file with information on the bsp statistics and a text file containing the list of images used as texture maps in the model faces. Each of these will be stored in files with extensions .bsp, .log.txt and .map

· Fly3D export plug-in operations

Export the scene to a bsp file using the supplied export plug-in expflybsp.dle. Do this using the File/Export menu command and selecting the Fly3D BSP file type. This causes the bsp tree to be built.

Make sure to save the bsp inside the flysdk\data directory. Create a sub-directory in flysdk\data named tutorial. This where all level data from the tutorials should be be stored.

{ To install the export plug-in, just copy the expflybsp.dle file to the 3dsmax\plugins directory before opening 3D Studio Max }

At this stage, we set the options for the export file:

- Light Radius (meters): this parameter is multiplied by the self illumination parameter value from the materials giving the final light radius for the object. For example, specifying a light radius of 20 meters, a material with 50 % self illumination gives a real light radius of 10 meters.

- Save # objects: this option saves all objects with names starting with the '#' character as .3ds files in the objects subdir from where the bsp files is being saved. Name all objects that will not make part of the bsp with this starting character as they will be used as dynamic objects (doors, player, guns projectiles, powerups, etc...).

- Save bsp log: this option saves a .txt file with the same name as the bsp file, including information on the bsp construction, nodes and faces. This facility records the statistics of the bsp tree, which can then be examined for effectiveness.

- BSP planes:

face aligned: used for closed enviroments only, the level must present a single in/out volume. With this option, all bsp planes will be aligned with level faces, making a bsp plane for each plane defined by the level faces.

axis aligned: used for landscapes and freespaces. The bsp planes are aligned only with X,Y and Z aixis. A maximum tree depth can be specified and will stop subdivision if that depth is reached. Landscapes are 2D bsp files that are good for race and strategy games. Freespaces are 3D bsp files used in space simulator and space strategy games.


Fly3D Tutorial 4 - Creating the level script .FLY file

Fly3D SDK

Tutorials

Home

Tutorial 4

Creating the level script .FLY file

· Introduction

Writing a script consists of specifying the global level parameters, the plug-ins to be included in the level and enumerating the instances of the plug-in classes used in the level with their parameter values. At the end of this tutorial you will have constructed a script with all the global parameters for the level which will be used in the lighting and visibility tutorials.

· flyEditor operations

1) Open the flyEditor.exe and click the new button

2) Save the new file to the same directory as the file from the previous tutorial (flysdk\data\turorial).

3) Specify the BSP file to be used in the level selecting the global tree item and double clicking on the bspfile list view item. This will show an open file dialogue and you must select the BSP from turorials 1 or 2.


Fly3D Tutorial 5 - Creating the level light map .LMP file

Fly3D SDK

Tutorials

Home

Tutorial 5

Creating the level light map .LMP file

· Introduction

The operations in this tutorial effect the construction of the light maps that are used to illuminate the scene. At the end of this tutorial you will have created the light maps (stored in a .lmp file). This caches the illumination of all self illuminated faces and light objects in the scene light maps.

· Fly utilities operations

1) Execute the flyLight.exe utility. In the flyEditor, use the Tools/Light menu option.

2) Select the .fly file you created in tutorial 3.

3) Select the lighting options from:

  • Shadows: shadows are calculated for each light map pixel (increasing the computation time for complex scenes).
  • Connectivity: when off, this enables co-planar faces which are not connected to share the same light map. This means that the total number of lightmaps is kept as low as possible although it also implies that many light map pixels will be redundant (mapping to space between such faces).
  • Light Radius and Light Value: overwrites original setting from the materials to facilitate editing at this stage.
  • Pixel Size: the desired light map pixel size. Small values will make the dynamic light slower.
  • Ambient Light: amount of light to add to all light pixels (0 to 255).

4) Press compute to start the lighting computations.


Fly3D Tutorial 6 - Creating the level .PVS file

Fly3D SDK

Tutorials

Home

Tutorial 6

Creating the level .PVS file

· Introduction

The operations in this tutorial calculates the PVS using the non-deterministic method described in the text. For a scene of high complexity, this program will run for several hours. After completion you will have computed all node to node visibility and enhanced the BSP tree with a connectivity matrix. The PVS will be stored in a flie with extension .pvs.

· Fly utilities operations

1) Execute the flyPVS.exe utility. In the flyEditor, use the Tools/View menu option.

2) Select the bsp file you created in tutorial 1 or 2.

3) Select the sampling cube resolution. For this tutoriual a 64x64 resolution is sufficient.

4) Save PVSlog: this saves a .txt file with the same name as the BSP file including information on the PVS construction. This facility records the statistics of the pvs connectivity matrix, which can be examined for effectiveness.

5) Visibility Sample Factor: a useful parameter that sets the volume sampling accuracy of the PVS calculation. The volume of each node is calculated and a sampling density specified (cubic metres/sample).


Fly3D Tutorials 7 - Adding Fly3D plug-ins

Fly3D SDK

Tutorials

Home

Tutorial 7

Adding Fly3D plug-ins

· Introduction

At this point a level has been created and preprocessed but there are no dynamic objects included in the level and thus no game to execute. This tutorial enables experimentation with the supplied plug-ins to give a introduction to the nature of game development using plug-in architecture as a development tool.

After completing this tutorial you will have a executable game.

· flyEditor operations

1) open the script file from tutorial 4 with the flyEditor

2) right click the plug-ins tree item and select insert from the popup menu

3) an open dialogue will show up, and you should select the walk.dll.

4) now we need to create a new person object from the walk.dll. This will be the player. Right click the person tree item and select insert from the popup menu. A new person object will be created and you can set its name to a chosen name like 'myplayer'.

5) fill in the following person object properties for your new player:

complex behavior can only be achieved using a large number of parameters, you can start using default values for this and experiment with different settings for parameters of your choice.

Parameter | Value | Description
colflag | 1 | sets collision on/off
mass | 1 | sets player mass (in this case >0)
radius | 1 | sets player collision radius (player collides as a sphere)
bump | 1 | bouncing factor (0.0 to 1.0)
friction | 1 | sliding factor (0.0 to 1.0)
active | 1 | activate on startup
height | 18.5 | player height (1.85m)
jumpforce | 0.006 | jump force (use space key to jump)
jumpforcetime | 100 | jump time
gravity | 0.002 | gravity applied to player
walkvel | 0.2 | walk velocity (use s,x,q,e keys to move)
rotvel | 0.1 | keyboard rotation factor (use arrows to rotate view)
mousespeed | 0.2 | mouse rotation factor (use mouse to rotate view)
zoomtime | 300 | zoom time in ms (use right mouse click to zoom)
zoomangle1 | 60 | standard view angle
zoomangle2 | 20 | zoom view angle
shield | 1 | player shield

6) Press the Save and Restart button on the tool bar or select the Flile/Restart menu option to restart the scene (this will activate all objects set to activate on startup)

7) Select the global tree view item and change the following global parameters:

Parameter | Value | Description
viewmindist | 1 | near plane distance
viewmaxdist | 1500 | far plane distance
player | myplayer | sets the player object
camera | myplayer | sets the camera object
camangle | 60 | player camera angle
mapmode | 1-15 | selects mapping layers (bit flag): bit 1 for texture map bit 2 for detail map bit 3 for light map bit 4 for fog map use 1 for texture only use 5 for texture and lightmap use 15 for all maping layers

8) Now you are ready to walk around. Turn the render on by selecting OpenGL on the tool bar or using the menu render option. Start simmulatig clicking the Simmulate tool bar button or using the F4 key. You should see the level from the players point of view in the render window (notice that as no birth pads have been created yet, the player will start up at co-ordinates 0,0,0 that must be inside the level).

9) Select the render window by clicking on it (or use the TAB key) and you should be able to move around.


Fly3D Tutorial 8 - How to model a dynamic object

Fly3D SDK

Tutorials

Home

Tutorial 8

How to model a dynamic object

The most important factor that distinguishes a dynamic object from a static object is the texture map. It is important that one texture map be derived for the complete object for run time efficiency.

The steps in buiding up a dynamic object are:

1) Build a polygon mesh model.

2) Render orthographic views of the object (front, side, top, back, etc). The numbers of view that will be required depends on the object complexity. All parts of the object must be visible and of sufficient projected area in 2D space.

3) Use a painting package to paint the textures on the views.

4) Create a single texture and copy/paste the required parts of the orthographic painted views into it. Notice that symmetric objects that have reflected textures should have both regions mapped onto the same area of the texture map. It is important for efficiency not to duplicate textures in the texture map.

5) Use the supplied utility (ProgMesh.exe) to precisely position the tetxure coordinates for each of the model faces into the desired position in the texture map.


Fly3D Tutorial 9 - Creating a new Fly3D plug-in

Fly3D SDK

Tutorials

Home

Tutorial 9

Creating a new Fly3D plug-in

· Introduction

At the end of this tutorial you will have created a new Fly3D plug-in to be used in your games. The plug-in will implement a single game object named blink_light. The object will be a dynamic light source that constantly changes its radius based on a predefined time interval.

· Visual C++ operations

1) Open the Visual C++ Fly3D Plug-ins Workspace

2) Select the menu option File/New to create a new project

3) Select the projects tab and the Fly3D Plug-in Wizard

4) Set the project location to the flysdk\plugin path and name the project 'tutorial'. Make sure to select 'add to curent workspace' to keep all Fly3D plug-in projects in a single workspace.

5) On the first wizard step, add a single class named 'blink_light'

6) On the second wizard step, add three parameters:

name: 'color' type: color
name: 'illumradius' type: float
name: 'blinktime' type: int

7) On the third wizard step, select the Fly3D SDK path and click Finish.

8) You should now be able to compile the plug-in with no errors.

9) Now we will add the blink light functionality. Open the tutorial.cpp file and add the following code to the blink_light::step function:

int blink_light::step(int dt)
{
// compute current radius
float r=illumradius*
((flyengine->cur_time%blinktime)/1000.0f);

// illuminate around
flyengine->send_bsp_message(
flyengine->bsp, pos, r, FLYOBJM_ILLUM,
  0, &color);

// return 0 as we have not moved (changed pos)
return 0;
}

10) If the blink_light is to be destroyed after say 30 seconds of illumination, set its life parameter to 30000 and add the following line anywhare in the blink_light::step function:

// subtract elapsed time from object's life
life-=dt;

When the blink_light's life value truns negative, it will be destroyed by the engine.

11) Use the ALT-F7 key to edit the project settings. On the link tab, change the output file name to '../tutorial.dll'. This will save the compiled dll to the flysdk\plugin directory with all other Fly3D plug-ins (make sure to change this option for the release and debug versions).

12) Compile the tutorial (flysdk\plugin\tutorial.dll should be built) and we are ready to add the plug-in object to the level from previous tutorials.

13) Run the plug-in (debug it) using the F5 key and select the flyEditor.exe to open (or just run a standalone copy of flyEditor if no debug is needed).

· flyEditor operations

1) Open the level .fly file cretated in previous tutorials and add the tutorial.dll to it just like in tutorial 7.

2) Add a new blink_light object and set its parameters as follows:

 active    = 1 (activate on startup)
color     = any color you choose for the light, but not
  black!
radius    = 100 (10 meters)
life      = 30000 (30 sec)
blinktime = 1000 (1 second)

This active parameters tells the engine to activate a copy of the object on scene startup. If we set it to 0, the blink_light will be on the stock and can be used as a parameter in another game object or activated by another game object (and will not be visible until then).

3) Run the level (setting the render and starting simmulation). You should see the blink_light illuminating the faces near its position (0,0,0). You can change its parameters and see the results in real-time in the render view.


Fly3D Tutorial 10 - Adding a new object to a Fly3D plug-in

Fly3D SDK

Tutorials

Home

Tutorial 10

Adding a new object to a Fly3D plug-in

· Introduction

After finishing this tutorial you will have added a new object to an existing Fly3D plug-in. The object we will add is a simple object that has a mesh representation and moves around bouncing on walls as a sphere.

· Visual C++ operations

1) Open the plug-in project created in last tutorial.

2) Add a new type to the enumeration on the beginning of tutorial.h:

enum
{
TYPE_BLINK_LIGHT=100000,
TYPE_BOUNCE_MESH,
}

3) Add the following lines to the end of the tutorial.h file:

class bounce_mesh : public bsp_object
{
public:
bounce_mesh() { type=TYPE_BOUNCE_MESH; };

// the obejct's mesh
mesh *objmesh;

// no step() is defined, using the particle base class step()

// this will handle drawing and collision with the object
mesh *get_mesh() { return objmesh; };

int get_custom_param_desc(int i,param_desc *pd);
bsp_object *clone();
};

class bounce_mesh_desc : public class_desc
{
public:
void *create() { return new bounce_mesh; };
char *get_name() { return "bounce_mesh"; };
int get_type() { return TYPE_BOUNCE_MESH; };
};

4) Add the following global variable to the beginning of the tutorial.cpp file:

bounce_mesh_desc cd_bounce_mesh;

5) The exported num_classes() function in the tutorial.cpp file should look like this as we now have two classes:

__declspec( dllexport )
int num_classes()
{
return 2;
}

6) The exported get_class_desc() function in the tutorial.cpp file should look like this as we now have two classes:

__declspec( dllexport )
class_desc *get_class_desc(int i)
{
switch(i)
{
case 0:
return &cd_blink_light;
case 1:
return &cd_bounce_mesh;
default: return 0;
}
}

7) Add the following lines to the end of the tutorial.cpp file:

bsp_object *bounce_mesh::clone()
{
bounce_mesh *tmp=new bounce_mesh;
*tmp=*this;
tmp->source=this;
return tmp;
}

int bounce_mesh::get_custom_param_desc(int i,param_desc *pd)
{
if (pd!=0)
switch(i)
{
case 0:
pd->type='3';
pd->data=&objmesh;
strcpy(pd->name,"objmesh");
break;
}
return 1;
}

· flyEditor operations

1) Open the level .fly file cretated in previous tutorials in flyEditor.

2) Add a new bounce_mesh object and set its parameters as follows:

 vel      = 0.1 0.1 0.1 (diagonal
  velocity)
mass     = 1.0 (object mass)
bump     = 1.0 (bumping factor)
friction = 1.0 (friction factor)
radius   = 10 (the object collision radius)
colflag  = 1 (turns collision detection on)
active   = 1 (activate on startup)
life     = 30000 (bounce for 30 seconds and die)
objmesh  = select any 3ds file to be used as the object's mesh

3) Run the level (setting the render and starting simmulation).

4) With the bouce_mesh object selected, click the activate button on the toolbar to add a new instance of the object to the simmulation. You should see the bounce_mesh moving and colliding with the level walls.


Fly3D Tutorial 11 - Creating a player object (observer)

Fly3D SDK

Tutorials

Home

Tutorial 11

Creating a player object (observer)

· Introduction

After finishing this tutorial you will have created a new game object that can be used as a player. The object will move around the level aquiring keys and mouse to guide its movement.

· Visual C++ operations

1) Open the Visual C++ Fly3D Plug-ins Workspace

2) Select the menu option File/New to create a new project

3) Select the projects tab and the Fly3D Plug-in Wizard

4) Set the project location to the flysdk\plugin path and name the project 'observer'. Make sure to select 'add to curent workspace' to keep all Fly3D plug-in projects in a single workspace.

5) On the first wizard step, add a single class named 'observer'

6) On the second wizard step, add three parameters:

name: 'rotvel' type: float
name: 'mousevel' type: float
name: 'moveforce' type: float
name: 'maxvel' type: float
name: 'veldamp' type: float

7) On the third wizard step, select the Fly3D SDK path and click Finish.

8) You should now be able to compile the plug-in with no errors

9) Open the observer.cpp file and put the following code over fly_message case FLYM_DRAWSCENE:

case FLYM_DRAWSCENE:
// draws scene viewed from camera
flyengine->set_camera(flyengine->cam);
flyengine->draw_bsp();
break;

10) Make the observer::init() fuction as follows:

void observer::init()
{
// initialize observer at random position in level
if (flyengine->get_random_point(pos,10)==0)
pos.null();
}

11) Replace the observer step function with the following code:

int observer::step(int dt)
{
if (node==0)     // if not in bsp (outside
  level on last frame)
add_to_bsp(); // add it to the bsp as it
  might be inside now

check_keys(dt); // process keys

// damp velocity
float len=vel.length();
if (len<0.1f)
vel.null();
else
{
vel/=len;
len-=dt*veldamp;
if (len>maxvel)
len=maxvel;
if (len<0.0f)
len=0.0f;
vel*=len;
}

life=dt; // keep alive
return particle::step(dt); // moves as particle
}

12) add the check_keys function as follows (also add its prototype to the observer.h file):

void observer::check_keys(int dt)
{
// direct input keys
unsigned char *diks=directx->diks;

// mouse smooth
static int lastmouse[2][2]={ { 0,0 },{ 0,0 } },lm=0;
float mousedx=(directx->dims.lX+lastmouse[0][0]+lastmouse[1][0])/3.0f;
float mousedy=(directx->dims.lY+lastmouse[0][1]+lastmouse[1][1])/3.0f;
lastmouse[lm][0]=directx->dims.lX;
lastmouse[lm][1]=directx->dims.lY;
lm=!lm;

// process keys
if (diks[0x38]) // ALT key
{
if (diks[0xcb]) // left arrow
vel-=X*(moveforce*dt);
if (diks[0xcd]) // right arrow
vel+=X*(moveforce*dt);
if (diks[0xc8]) // up arrow
vel+=Y*(moveforce*dt);
if (diks[0xd0]) // down arrow
vel-=Y*(moveforce*dt);
if (diks[0x1f]) // S key
vel-=Z*(moveforce*dt);
if (diks[0x2d]) // X key
vel+=Z*(moveforce*dt);
}
else
{
if (diks[0xc8]) // up arrow
rotate(-dt*rotvel,X);
if (diks[0xd0]) // down arrow
rotate(dt*rotvel,X);
if (diks[0xcb]) // left arrow
rotate(dt*rotvel,Y);
if (diks[0xcd]) // right arrow
rotate(-dt*rotvel,Y);
if (diks[0x10]) // Q key
vel-=X*(moveforce*dt);
if (diks[0x12]) // E key
vel+=X*(moveforce*dt);
if (diks[0x1f]) // S key
vel-=Z*(moveforce*dt);
if (diks[0x2d]) // X key
vel+=Z*(moveforce*dt);
}

if (diks[0x1e]) // A key
rotate(dt*rotvel,Z);
if (diks[0x20]) // D key
rotate(-dt*rotvel,Z);

if (mousedx) // mouse X
rotate(-mousedx*mousevel,Y);
if (mousedy) // mouse Y
rotate(mousedy*mousevel,X);
}

12) Use the ALT-F7 key to edit the project settings. On the link tab, change the output file name to '../observer.dll'. This will save the compiled dll to the flysdk\plugin directory with all other Fly3D plug-ins (make sure to change this option for the release and debug versions).

13) Compile the tutorial (flysdk\plugin\observer.dll should be built).

14) You can now add this plugin to a level and set the global engine parameter camera and player to point to a active instance of the observer class. It will allow you to fly around the level with ease.

· flyEditor operations

1) Open the flyEditor.exe and click the new button

2) Save the new file (objesrver.fly) to the same directory as the file from the previous tutorials (flysdk\data\turorial).

3) Specify the BSP file to be used in the level selecting the global tree item and double clicking on the bspfile list view item. This will show an open file dialogue and you must select the BSP from turorials 1 or 2.

4) Now we need to create a new observer object from the observer.dll. This will be the player.
Insert the observer.dll to the level by right clicking the tree item Plugins and selecting insert.
Right click the new observer tree item and select insert from the popup menu.
A new observer object will be created and you can set its name to a chosen name like 'myplayer'.

5) Fill in the following observer object properties for your new player:

Parameter | Value | Description
colflag | 1 | sets collision on/off
mass | 1 | sets player mass (in this case >0)
radius | 20 | sets player collision radius to 2m (player collides as a sphere)
bump | 1 | bouncing factor (0.0 to 1.0)
friction | 1 | sliding factor (0.0 to 1.0)
active | 1 | activate on startup
rotvel | .1 | velocity for keybord rotation (arrows keys)
mosevel | .1 | velocity for mouse rotation
moveforce | .01 | force applyed for movement (S,X and slide keys)
maxvel | .5 | maximum velocity for the observer
veldump | .001 | damping factor for observer velocity

6) Activate an instance of the player by selectig the player and clinking the activate button on the tool bar (this must be done or you will not be able to set the camera and player global parameters to point to the observer as they can only point to active instances of objects).

7) Set the following global parameters by selecting the Glabal tree view item:

Parameter | Value | Description
viewmindist | 10 | sets near plane distance
viewmaxdist | 1500 | sets far plane distance
camangle | 60 | set camera view angle
camera | myplayer | set camera object
player | myplayer | set player object
mapmode | 15 | view all mapping layers

8) Now you are ready to fly around. Turn the render on by selecting OpenGL on the tool bar. Start simmulatig clicking the Simmulate tool bar button or using the F4 key. You should see the level from the observers point of view in the render window.

9) Select the render window by clicking on it (or use the TAB key) and you should be able to move around using the S,X,ARROW keys


Fly3D Tutorial 12 - Creating a front-end

Fly3D SDK

Tutorials

Home

Tutorial 12

Creating a front-end

· Introduction

After finishing this tutorial you will have created a new front-end executable. This front-end will be able to run any Fly3D level and is the simplest possible front end. It creates a window, sets full screen mode, initialises the engine, loads a level and starts the game

· Visual C++ operations

1) Open the Visual C++ Fly3D Workspace

2) Select the menu option File/New to create a new project

3) Select the projects tab and the Win32 Application type

4) Set the project location to the flysdk\frontend path and name the project 'flyfe'. Make sure to select 'add to curent workspace' to keep all Fly3D front-ends projects in a single workspace.

5) Select an empty project and add the following flyfe.cpp file to the project:

#include <windows.h>
#include <Fly3D.h>

char szTitle[100]="MyGame Title";
char szWindowClass[100]="MyGame";

// loads the menu level
void LoadLevel(HWND hWnd, HINSTANCE hInst)
{
init_engine(hWnd,hInst,FLYAPPID_FLYFRONTEND);
init_directx();
init_render(FLY_RENDER_OPENGL);

fullscreen=1;
rend->SetFullScreen();

flyengine->open_fly_file("menu/menu.fly");
flyengine->init_texture_cache();
InvalidateRect(hFlyWnd, 0, 0);
}

// main window message processing
LRESULT CALLBACK WinFunc (HWND hWnd, UINT mens, WPARAM wParam, LPARAM lParam)
{
switch (mens)
{
// window resize
case WM_SIZE:
if (rend)
rend->ResizeView(LOWORD(lParam),HIWORD(lParam));
break;

// window activation
case WM_ACTIVATE:
if (flyengine)
if (LOWORD(wParam)==WA_INACTIVE || flyengine->con.mode)
flyengine->noinput=1;
else
flyengine->noinput=0;
break;

// quit app
case WM_DESTROY:
PostQuitMessage
  (0);
break;
}

return DefWindowProc(hWnd, mens, wParam, lParam);
}

int WINAPI WinMain (HINSTANCE hInst, HINSTANCE hPrev, LPSTR lp, int nCmd)
{
WNDCLASS wcl;
MSG msg;

// register window class
wcl.style = CS_HREDRAW | CS_VREDRAW;
wcl.lpfnWndProc = (WNDPROC)WinFunc;
wcl.cbClsExtra = 0;
wcl.cbWndExtra = 0;
wcl.hInstance = hFlyInstance;
wcl.hIcon = LoadIcon(NULL, IDI_WINLOGO);
wcl.hCursor = 0;
wcl.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wcl.lpszMenuName = NULL;
wcl.lpszClassName = szWindowClass;
if (!RegisterClass (&wcl))
{
MessageBox (0, "Can't register
  Window", "ERROR", MB_OK);
return 0;
}

// cerate main window
HWND hWndMain = CreateWindowEx(0,szWindowClass,szTitle,WS_POPUP,0,
  0,
GetSystemMetrics(
  SM_CXSCREEN ),GetSystemMetrics( SM_CYSCREEN ),
NULL,NULL,hFlyInstance,NULL);

// load the level
ShowWindow (hWndMain, SW_MAXIMIZE);
LoadLevel (hWndMain, hFlyInstance);

// main loop
while (1)
{
while (PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE)
  == TRUE)
{
if (GetMessage(&msg, NULL, 0,
  0))
{
if (flyengine &&
  (
(msg.message==WM_KEYDOWN
  && msg.wParam==VK_ESCAPE) ||
(msg.message==WM_CHAR
  && flyengine->con.mode && msg.wParam!=VK_ESCAPE)))
flyengine->con.key_press(msg.wParam);
TranslateMessage(&msg);
DispatchMessage(&msg);
}
else
{
// frees engine, render,
  directx and quits app
free_engine();
free_render();
free_directx();
return TRUE;
}
}

if (rend && flyengine)
if (flyengine->step()) // simmulate
rend->DrawView();
  // draw view
}
}

6) At the project settings change the follwing configurations in the Release and Debug versions:

- add the path '..\..\lib' to the 'Additional include directory' and 'Additional library path'.
- change the 'Output file name' to '..\..\flyfe.exe' so that the exe is placed with the other front-ends at the flysdk root path.
- set the 'Object/library modules' option to 'fly3d.lib user32.lib'

7) Compile and run the new front-end. It will set full screen and run the menu.fly level.


Fly3D SDK Reference

Home

Globals Reference

Defined Constants
Defined Macros
Global Variables
Global Functions

Objects Reference

vector | mat4x4 | boundbox
plane | console | face
local_system | base_object | particle
mesh | anim_mesh | stripfan_mesh
bezier_curve | bezier_patch | bsp_node
bsp_object | static_mesh | light_map
light_map_pic | light_vertex | sound
param_desc | class_desc | fly_pak
flypakutil | flydll | flydllgroup
flyEngine | directX | picture
textcache | textcacheGL | render
renderGL |  |


Fly3D SDK Reference

Globals Reference

Defined Constants

Constant | Value
FLYMP_GUARANTEED | 0x80000000
FLYMP_BROWSETIME | 2000
FLYMP_PLAYERDATASIZE | 40
FLYMP_MAXPLAYERS | 16
FLYMP_MAXSERVICES | 16
FLYMP_MAXGAMES | 16
FLYMP_MSG_JOIN | 9171|FLYMP_GUARANTEED
FLYMP_MSG_QUIT | 9172|FLYMP_GUARANTEED
FLYMP_MSG_FLYFILE | 9173|FLYMP_GUARANTEED
FLYMP_NOMP | 0
FLYMP_CLIENT | 1
FLYMP_SERVER | 2
FRAND | (((rand()%10000)-5000)/5000.0f)
FABSRAND | ((rand()%10000)/10000.0f)
SMALL | 1.0e-4f
BIG | 1.0e+10f
M_Pi2 | 1.570796326795f
M_Pi | 3.14159265359f
M_2Pi | 6.28318530718f
PiOver180 | 1.74532925199433E-002f
PiUnder180 | 5.72957795130823E+001f
FP_ONE_BITS | 0x3F800000
MAX_ELEMDRAW | 16384
MAX_LIGHTMAP | 8192
MAX_PICTURES | 1024
MAX_VERT | 4096
MAX_HWLIGHTS | 8
MAX_TEXTURE_UNITS | 4
MAX_LATEDRAW_LAYERS | 8
NUM_DEFAULT_PARAM | 12
FLYM_INITSCENE | 1000
FLYM_UPDATESCENE | 1001
FLYM_DRAWSCENE | 1002
FLYM_DRAWTEXT | 1003
FLYM_CLOSESCENE | 1004
FLYM_MPMESSAGE | 1005
FLYM_MPUPDATE | 1006
FLYOBJM_CHANGEPARAM | 2000
FLYOBJM_ILLUM | 2001
FLYOBJM_STATICILLUM | 2002
FLYOBJM_DYNILLUM | 2003
FLYOBJM_DAMAGE | 2004
FLYAPPID_NONE | 0
FLYAPPID_FLY | 1
FLYAPPID_FLYEDITOR | 2
FLYAPPID_LIGHTBSP | 3
FLYAPPID_FLYSERV | 4
FLYAPPID_FLYOCX | 5
FLYAPPID_VIEWBSPGL | 6
TYPE_STATIC_MESH | -1
MAPPING_NUM | 4
MAPPING_OPTIONS | 16
MAPPING_TEXTURE | 1
MAPPING_DETAIL | 2
MAPPING_LIGHTMAP | 4
MAPPING_FOGMAP | 8
MESHCN_IMPLODE | 1
MESHCN_FACENORM | 2
MESHCN_VERTNORM | 4
MESHCN_BBOX | 8
MESH_EDGES | 16
PATCH_EVAL_POINT | 1
PATCH_EVAL_TEXTCOORD | 2
PATCH_EVAL_NORMAL | 4
CONSOLE_MAX_LINES | 128
CONSOLE_COL | 40
CONSOLE_LIN | 30
FONTS_IMG_SIZE | 128
FONTS_SIZE | 16
FONTS_NUM | 8


Fly3D SDK Reference

Globals Reference

Defined Macros

Macro | Definition
vec_dot(v1,v2) | ((v1).x*(v2).x+(v1).y*(v2).y+(v1).z*(v2).z)
ISZERO(a) | ((a)>-SMALL && (a)<SMALL)
FP_BITS(fp) | (*(DWORD *)&(fp))
FP_ABS_BITS(fp) | (FP_BITS(fp)&0x7FFFFFFF)
FP_SIGN_BIT(fp) | (FP_BITS(fp)&0x80000000)
PVS_TEST(from,to) | (*(pvs + (from)*pvsrowsize + ((to)>>3)) & (1 << ((to) & 7)))


Fly3D SDK Reference

Globals Reference

Global Variables

flyEngine *flyengine

Interface with engine core.

directX *directx

Interface with direct input, direct sound and direct play.

textcache *tc

Interface with texture cache (load, selection and update of textures)

render *rend

Interface with the current selected render.

GUID FLYGUID

The Fly3D application GUID

int screen_sx
int screen_sy

Render screen size in pixels

HWND hFlyWndMain

Frontend window handle

HINSTANCE hFlyInstance

Frontend instance handle

int textfilter

Flag turning texture filter on/off

int mipmap

Flag turning mipmap on/off

int ntextureunits

Number of available hardware texture units for multitexture.

int nhwlights

Number of hardware lights available.

int numvideomodes

Number of available fullscreen video modes in videomodes array.

int selvideomode

Current selected fullscreen video mode from videomodes array.

DEVMODE *videomodes

The fullscreen video modes array.

int fullscreen

Fullscreen flag (FALSE for window mode).

int bitdepth

Current bit render depth (16, 24 or 32).

RECT winrect

The window rectangle while in window mode.


Fly3D SDK Reference

Globals Reference

Global Functions

void init_directx(HWND hWnd,HINSTANCE hInst)

Initializes the directx global variable. It must be called by the frontend before using direct input, direct sound and direct play.

void free_directx()

Frees the directx global variable.

void init_render(int type,HWND hwnd)

Initializes the render global variable. It must be called by the frontend before rendering.

void free_render()

Frees the render global variable.


class anim_mesh

Objects Reference

class anim_mesh : public mesh

Definition

class anim_mesh : public mesh
{
public:
int nframes,texpic;
vector *ao_vert;
vector *ao_bbox;
int nstripfan,nstripfanvert,*stripfancount,*stripfanvert;
vertex *vertdata;

anim_mesh()
{
ao_vert=0;
ao_bbox=0;
nframes=0;
nstripfan=0;
nstripfanvert=0;
stripfancount=0;
stripfanvert=0;
vertdata=0;
texpic=-1;
}

void reset();
void compute_bbox();
int load_fao(char *name);
void set_key(float key);
void set_key(int key);
void draw();

virtual ~anim_mesh()
{ reset(); };
};

Data Members

Member | Type | Description
nframes | int | number of key frames in animation
texpic | int | the texture picture applied to the mesh
ao_vert | vector * | keyframe vertices (nv*sizeof(vector)*nframes)
ao_bbox | vector * | keyframe bounding boxes (nframes*2*sizeof(vector))
nstripfan | int | number of strips/ans
nstripfanvert | int | number of vertices in strip/fan vertex array
stripfancount | int * | strip/fan vertex count array (nstripfan*sizeof(int))
stripfanvert | int * | vertex indices into ao_vert (nstripfanvert*sizeof*(int))
vertdata | vertex * | strip/fan vertex array (nstripfanvert*sizeof(vertex))

Methods

reset, compute_bbox, load_fao, set_key, draw

Remarks

This class implements an animated mesh. The mesh animation is defined by keyframes and each keyframe if made of an array of vertex positions. The mesh can be represented by a group of strip/fans or just the separate triangles. The complete mesh must have a single texture and to interpolate the animation, use the set_key function.

See Also

vector, mesh


anim_mesh::compute_bbox

Prototype

void compute_bbox()

Parameters

None

Return Value

None

Remarks

This function computes the boudboxes for all keyframes and stores them in the ao_bbox array.


anim_mesh::draw

Prototype

void draw()

Parameters

None

Return Value

None

Remarks

This function draws the animated mesh at its current animation frame. If the mesh was created/loaded with strips/fans, they are used for faster drawing. If no strip/fan information is available, separate triangles are drawn.


anim_mesh::load_fao

Prototype

int load_fao(char *name)

Parameters

Parameter | Type | Description
name | char * | filename for .fao file

Return Value

None

Remarks

This function loads a .fao animated mesh file into the class. All keyframes and texture are loaded and bounding boxes, and normals calculated. If a .fao object includes strip/fans they are also loaded.


anim_mesh::reset

Prototype

void reset()

Parameters

None

Return Value

None

Remarks

This function resets the mesh and frees all allocated resources.


anim_mesh::set_key

Prototype

void set_key(int key)
void set_key(float key)

Parameters

Parameter | Type | Description
key | int | integer key frame (0 - numframes)
key | float | float key frame (0 - 1.0)

Return Value

None

Remarks

These functions are used to set the current animation key. The integer version of the function is faster, but can only set the mesh to one of the predefined keyframes. The float version, linearly interpolates the two closest key frames to generate a smooth animation between keyframes.


class boundbox

boundbox

Definition

class boundbox
{
public:
vector min,max;

void reset()
{
min.vec(BIG,BIG,BIG);
max.vec(-BIG,-BIG,-BIG);
};
void add_point(vector &p);
void add_point(float x,float y,float z);
int ray_intersect(vector& ro,vector& rd,float& tnear,float& tfar);
};

Data Members

Member | Type | Description
min | vector | minimum corner of bounding box
max | vector | maximum corner of bounding box

Methods

reset, add_point, ray_intersect

Remarks

This class impements a axis aligned bounding box (AABB). The min vector specifies the minimum co-ordinates for the AABB and max the maximum co-ordinates.

See Also

vector


boundbox::reset

Prototype

void reset()

Parameters

None

Return Value

None

Remarks

This method resets the bounding box by setting the min vector to (BIG,BIG,BIG) and the max vector to (-BIG,-BIG,-BIG).
Use this method before calling the add_point method when creating a new bounding box.


boundbox::add_point

Prototype

void add_point(vector &p)
void add_point(float x,float y,float z)

Parameters

Parameter | Type | Description
p | vector& | point to add
x | float | x coord. of point to add
y | float | y coord. of point to add
z | float | z coord. of point to add

Return Value

None

Remarks

This method enlarges the bounding box in order for it to contain the specified point.
When creating a bounbox for a mesh, call the reset method and loop calling this function with all mesh vertices.


boudbox::ray_intersect

Prototype

int ray_intersect(vector& ro,vector& rd,float& tnear,float& tfar)

Parameters

Parameter | Type | Description
ro | vector& | ray origin
rd | vector& | ray direction
tnear | float& | returns near collision distance
tfar | float& | returns far collision distance

Return Value

Returns 0 if no collision is found, otherwise a collision was found.

Remarks

This method computes a ray intersection with the bounding box.
If a collision is found, the tnear and tfar parameters will be set to the distance from the ray origin where the ray intersected the bounding box.


bezier_curve

class bezier_curve : public base_object

Definition

class bezier_curve : public base_object
{
public:
float *p;
int np,ns,dim;
vector pivot;

bezier_curve()
{ p=0; reset(); };
virtual ~bezier_curve()
{ reset(); };

void reset();
void set_dim(int ndim);
void add_point(float *f);
void evaluate(float u,float *f);
void evaluate_tangent(float u,float *f);
int adaptative_subdiv(float maxerror,float *points,int maxpoints);
int load_bez(char *file);
float length();
};

Data Members

Member | Type | Description
p | float * | array of points (np*dim floats)
np | int | number of points in array
ns | int | number of curve segments
dim | int | dimension for each point
pivot | vector | position in 3D space for the center of the curve

Methods

reset, set_dim, add_point, evaluate, evaluate_tangent, adaptative_subdiv, load_bez, length

Remarks

This class implements a Bezier curve of any dimension (1D, 2D, 3D, etc...).

The curve and tangent can be evaluated at any point, and the curve can be adaptively subdivided until the curve error is less then a maximum error factor.

See Also

vector, bezier_patch


bezier_curve::reset

Prototype

void reset()

Parameters

None

Return Value

None

Remarks

Frees all data allocated for the curve control points and resets the curve to empty (no control points).


bezier_curve::length

Prototype

float length()

Parameters

None

Return Value

Returns the aproximate length for the Bezier curve.

Remarks

The curve is subdivided into small line segments (equal parametric intervals) and the sum of the length of all line segments is returned.


bezier_curve::set_dim

Prototype

void set_dim(int ndim)

Parameters

Parameter | Type | Description
ndim | int | new dim value

Return Value

None

Remarks

This function sets the number of co-ordinates in each point of the curve.
Setting ndim to 3 will make a curve in 3D space.


bezier_curve::add_point

Prototype

void add_point(float *f)

Parameters

Parameter | Type | Description
f | float * | pointer to first co-ordinate of the new point to add

Return Value

None

Remarks

This method adds a new point to the Bezier curve.
The number of floats pointed to by the parameter f must be equal to the curve dimentionality (dim).


bezier_object::load_bezier

bezier_curve::load_bez

Prototype

int load_bez(char *file)

Parameters

Parameter | Type | Description
file | char * | filename for a text .bez curve to load

Return Value

Returns 0 if file not found or reading error, otherwise loading occured.

Remarks

This method loads a Bezier curve from a text .bez file.


bezier_curve::evaluate

Prototype

void evaluate(float u,float *f)

Parameters

Parameter | Type | Description
u | float | value from 0.0 to 1.0 specifying the position in the curve to be evaluated
f | float * | pointer where to write the evaluated point

Return Value

None

Remarks

This function evaluates a Bezier curve point at the specified position.


bezier_curve::evaluate_tangent

Prototype

void evaluate_tangent(float u,float *f)

Parameters

Parameter | Type | Description
u | float | value from 0 to 1 specifying position in the curve to be evaluated
f | float * | pointer where to write the evaluated curve tangent

Return Value

None

Remarks

This function evaluates a Bezier curve tangent at the specified position.


bezier_curve::adaptative_subdiv

Prototype

void adaptative_subdiv(float maxerror,float *points,int maxpoints)

Parameters

Parameter | Type | Description
maxerror | float | the curve maximum error
points | float * | pointer to an array of floats to receive the subdivided points
maxpoints | int | the total number of floats in the points array

Return Value

None

Remarks

This function recursively subdivides the Bezier curve adaptatively. It subdivides segments that the midpoint distance to the actual curve is greater than the maxerror value.

At the end of the subdivision, the points array will have the curve points (each point a float from 0.0 to 1.0) where to intepolate the curve to get the actual adaptively subdivided curve.


class bezier_patch

class bezier_patch : public base_object

Definition

class bezier_patch : public base_object
{
public:
int mode; // 2 for quadratic and 3 for cubic
vector *p; // the surface control points
vector *t; // the surface texture control points
int np, // num points
npu, // num points in u dir
npv, // num points in v dir
nsu, // num segments in u dir
nsv; // num segments in u dir

int levelu,levelv; // subdivision level in u and v
int nvertu,nvertv; // surface num vertices in u and v
int texpic,lm; // texture and lightmap
vector *surf; // discretized surface
vector pivot; // the pivot position

void reset();
int load_pch(char *file);
void build_loft(bezier_curve *shape,bezier_curve *path,int texture,int lightmap,float tileu,float tilev);
void evaluate(int evaltype,float u,float v,vector *dest);
void build_surface();
void illuminate(vector& p,float rad,vector& color,int shadows);
void draw(int nleveldrop=0);
mesh *build_mesh();

bezier_patch() { p=0; t=0; surf=0; reset(); };
~bezier_patch() { reset(); };
};

Data Members

Member | Type | Description
mode | int | Bezier patch mode: 3 for quadratic 4 for cubic
pivot | vector | pivot position
p | vector * | the patch control points array
t | vector * | the patch coltrol points tetxure coordinates array (x,y) for texture map co-ordinates (z,w) for lightmap texture co-ordinates
np | int | number of points in control points array
npu | int | number of points in u dir
npv | int | number of points in v dir
nsu | int | number of segments in u dir
nsv | int | number of segments in v dir
levelu | int | subdivision level in u
levelv | int | subdivision level in v
nvertu | int | number of discretized vertices in u dir nvertu = (1<<levelu)+1
nvertv | int | number of discretized vertices in v dir nvertv = (1<<levelv)+1
texpic | int | texture applyed to the patch (-1 for none)
lm | int | light_map applyed to the patch (-1 for none)
surf | vector * | discretized surface points 2 vectors per entry (point and tetxure co-ordinates) size = 2*sizeof(vector)*nvertu*nvertv

Methods

reset, build_loft, evaluate, build_surface, build_mesh, illuminate, draw, load_pch

Remarks

This class implements a Bezier patch. The patch can have any number of segments in u and v directions. The patch is made of several connected cubic or quadratic Bezier patches (nsu is the numbre of patches in the u dir and nsv in the v dir).

For quadratic patches:
nsu = (spu-2)/2
nsv = (spv-2)/2

For cubic patches:
nsu = (spu-1)/2
nsv = (spv-1)/2

The surface is discretized based on the subdivision level. The number of vertices in u and v dir are:

nvertu = (1<<levelu)*nsu+1
nvertv = (1<<levelv)*nsv+1

At run-time, the surface car be draw at any level of detail up to its current selected level. The draw function includes a parameter that represents the number of levels of detail to drop on draw. The numbrer of vertices skipped (col/row draw loop increment) on each direction is:

nvertskip = (1<<nleveldrop)

See Also

vector, bezier_curve


bezier_patch::build_loft

Prototype

void build_loft(bezier_curve *shape,bezier_curve *path,int texture,int lightmap,float tileu,float tilev);

Parameters

Parameter | Type | Description
shape | bezier_curve * | shape curve
path | bezier_curve * | path curve
texture | int | the texture map
lightmap | int | the light map
tileu | float | tetxure map tile in u dir
tilev | float | tetxure map tile in v dir

Return Value

None

Remarks

This function builds the patch for a shape/path pair of Bezier curves.


bezier_patch::build_mesh

Prototype

mesh *build_mesh();

Parameters

None

Return Value

Returns the mesh object representing the patch. Must be deleted by caller when not in need any more.

Remarks

This function generates a mesh object equivalent to the discretized patch surface. It is used for collision detection with the patch.


bezier_patch::build_surface

Prototype

void build_surface();

Parameters

None

Return Value

None

Remarks

This function discretize the patch into the surf array.
It finds an independent subdivision level to use in u and v based on the flyengine curve error factor.


bezier_patch::draw

Prototype

void draw(int nleveldrop=0);

Parameters

Parameter | Type | Description
nleveldrop | int | number of levels of detail to drop on draw (0 for full detail)

Return Value

None

Remarks

This function draws the patch using triangle strips.
The current patch level of detail can be dropped by the nleveldrop parameter.


bezier_patch::evaluate

Prototype

void evaluate(int evaltype,float u,float v,vector *dest)

Parameters

Parameter | Type | Description
evaltype | int | bit field specifying what to evaluate: bit 1 (1) - point (PATCH_EVAL_POINT) bit 2 (2) - texture co-ordinates (PATCH_EVAL_TEXTCOORD) bit 3 (4) - normal (PATCH_EVAL_NORMAL)
u | float | u co-ordinate
v | float | v co-ordinate
dest | vector * | buffer where to write evaluated data

Return Value

None

Remarks

This function evaluates the Bezier patch.
The u and v parameters must be in the range 0.0 to 1.0.
Use the evaltype modifier to specify what should be evaluated.
The dest pointer must point to at least the number of selected values to be evaluated by evaltype.


bezier_patch::load_pch

Prototype

int load_pch(char *file)

Parameters

Parameter | Type | Description
file | char * | filename for a .pch file to load

Return Value

Returns TRUE if loading was OK, FALSE on any error.

Remarks

This function loads the patch from a text file in the .pch format.


bezier_patch::illuminate

Prototype

void illuminate(vector& p,float rad,vector& color,int shadows);

Parameters

Parameter | Type | Description
p | vector& | light point
rad | float | light radius
color | vector& | light color
shadows | int | shadows flag: 0 - no shadows 1 - shadows from specific object (shadow_obj) 2 - shadows from any object

Return Value

None

Remarks

This function illuminates the patch light_map pixles based on the light position, radius and color.
Shadows can be computed for a specific object or all objects using the shadows flag.


bezier_patch::reset

Prototype

void reset()

Parameters

None

Return Value

None

Remarks

This function frees all data allocated by the patch.


class base_object

Definition

class base_object
{
public:
char name[32];
char long_name[32];
base_object *next_obj;

base_object()
{ next_obj=0; name[0]=long_name[0]=0; };

virtual ~base_object()
{ ; };
};

Data Members

Member | Type | Description
name | char[] | object small name
long_name | char[] | object long nome
next_obj | base_object * | next object in the linked list

Methods

None

Remarks

This class is the base class for all objects. Several other classes from the engine derive from this class. It holds the object name and pointer to next object in the specific object linked list.

See Also

bsp_object


class plane

class bsp_node : public plane

Definition

class bsp_node : public plane
{
public:
bsp_node *child[2];
bsp_object
            *elem, **last_elem;
int leaf;
vector color;

bsp_node()
{ child[0]=child[1]=0; elem=0; leaf=-1; last_elem=&elem; };

virtual ~bsp_node();
};

Data Members

Member | Type | Description
child | char[] * | the two children
elem | bsp_object * | linked list of elements in node (if this is a leaf node)
last_elem | bsp_object ** | pointer to last element in elem linked list
leaf | int | leaf index (-1 if not a leaf node)
color | vector | ambient color of node (if this is a leaf node)

Methods

None

Remarks

This class implements a bsp tree node. All nodes at the end of the tree are considered leaves and they include a linked list of elements (Fly3D plug-in objects) inside the node and node ambient color.

See Also

vector, plane, bsp_node, bsp_object


class bsp_object

class bsp_object : public base_object, particle, local_system

Definition

class bsp_object : public base_object, particle, local_system
{
public:
int type;
int active;
vector rot;
bsp_object *next_elem;
bsp_object *source;
bsp_node *node;

bsp_object()
{ node=0; col_flag=0; source=0; next_elem=0; type=0; };

void add_to_bsp();
void remove_from_bsp();
virtual int step(int dt)
{ return particle::step(dt); };

virtual bsp_object *clone()
{ return 0; };

virtual mesh *get_mesh()
{ return 0; };

virtual void init()
{ ; };

int get_param_desc(int i,param_desc *pd);

virtual int get_custom_param_desc(int i,param_desc *pd)
{ return 0; };

virtual mesh *ray_intersect(vector& ro,vector& rd,vector& ip,float&
dist,int &facenum,float rad=0.0f);

virtual int message(vector& p,float rad,int msg,int param,void *data)
{ return 0; };

virtual void draw();
void load_default_params(fly_pak *file,char *sec);
void load_params(fly_pak *file,char *sec);

virtual ~bsp_object()
{ if (node) remove_from_bsp(); };
};

Data Members

Member | Type | Description
type | int | the object type (Fly3D plug-in type)
active | int | active flag (FALSE for inactive, TRUE activate on startup)
latedraw | int | last frame the object was draw
rot | vector | object rotation
next_elem | bsp_object * | next element in objects node linked list
source | bsp_object * | the object this one was cloned from (NULL if original object)
node | bsp_node * | the bsp_node the object is in

Methods

add_to_bsp, remove_from_bsp, step, clone, get_mesh, init, get_param_desc, get_custom_param_desc, ray_intersect, ray_intersect_test, message, draw, load_default_params, load_params

Remarks

This class implements a bsp_object. All objects created in Fly3D plug-ins must derive from this class. It is the base class for all objects that will be included in the bsp. New object behavior is implemented by sub-classing the class and implementing its virtual functions.

See Also

vector, bsp_node


bsp_object::add_to_bsp

Prototype

void add_to_bsp()

Parameters

None

Return Value

None

Remarks

This function adds the current object to the bsp tree. The current object position in 3D world space (pos) is used to find the bsp node the object is in and the object is added to that node's elements linked list.


bsp_object::clone

Prototype

virtual bsp_object *clone()

Parameters

None

Return Value

It must return a new class with the same parameters as the current class.

Remarks

This virtual function is used to clone the object. It must be implemented by all sub-classes or no object will be created.


bsp_object::draw

Prototype

virtual void draw()

Parameters

None

Return Value

None

Remarks

This virtual function is used for drawing the object and derived classes should implement it when needed.

Its default behavior is to call the get_mesh function and if a mesh is returned it calls the mesh draw function. So, if neither this function nor get_mesh is implemented the object will not be drawn.


bsp_object::get_custom_param_desc

Prototype

virtual int get_custom_param_desc(int i,param_desc *pd)

Parameters

Parameter | Type | Description
i | int | parameter index
pd | param_desc * | parameter desc to be filled

Return Value

If pd=0, the number of custom parameters.

Remarks

This virtual function must be implemented by all sub-classes. It returns the number of parameters the object has and each parameter description.

When called with pd=0, it must return the number of parameters. When pd<>0, it fill the description variable pd with information on the parameter index i.


bsp_object::get_mesh

Prototype

virtual mesh *get_mesh()

Parameters

None

Return Value

Returns a mesh representation for the object or NULL if none exists.

Remarks

This virtual function is used for querying the mesh representation of the object and derived classes should implement it when needed. If this function is implemented, the default draw, ray_intersect and ray_intersect_test will use it and they do not need to be defined in the derived class.

Its default behavior is to return 0.


bsp_object::get_param_desc

Prototype

int get_param_desc(int i,param_desc *pd)

Parameters

Parameter | Type | Description
i | int | parameter index
pd | param_desc * | parameter desc to be filled

Return Value

If pd=0, the number of custom parameters.

Remarks

This function implements the object standard parameters. All sub-classes must have these 12 parameters:

pos, vel, force, rot, life, colflag, mass, radius, bump, friction, active, latedraw


bsp_object::init

Prototype

virtual void init()

Parameters

None

Return Value

None

Remarks

This virtual function is called on object initialization. In it you can do whatever initialization your object needs.

Its default behavior is to do nothing.


bsp_object::load_default_params

Prototype

void load_default_params(fly_pak *file,char *sec)

Parameters

Parameter | Type | Description
file | flly_pak * | .fly file
sec | char * | section

Return Value

None

Remarks

This function loads all default parameters from a .fly file.


bsp_object::load_params

Prototype

void load_params(fly_pak *file,char *sec)

Parameters

Parameter | Type | Description
file | fly_pak * | .fly file
sec | char * | section

Return Value

None

Remarks

This function loads the object parameters from a .fly file


bsp_object::message

Prototype

virtual int message(vector& p,float rad,int msg,int param,void *data)

Parameters

Parameter | Type | Description
p | vector& | position
rad | float | radius
msg | int | type
param | int | parameter
data | void * | general pointer parameter

Return Value

Returns 0 for passing the message on, <>0 for stopping message.

Remarks

This virtual function processes messages for the object. It must be implemented if the object needs to receive any messages. Returning 0 will let the message pass on to next object that is in its radius, returning <>0 will stop the message and return the value to the caller immediately.


bsp_object::ray_intersect

Prototype

virtual mesh *ray_intersect(vector& ro,vector& rd,vector& ip,float& dist,int& facenum,float rad=0.0f)

Parameters

Parameter | Type | Description
ro | vector& | ray origin
rd | vector& | ray direction
ip | vector& | intersection point
dist | float& | intersection distance
facenum | int& | intersected face index
rad | float | collision radius

Return Value

Returns the intersected mesh or NULL for no intersection.

Remarks

This virtual function implements a ray intersection with the object. It should return the closest collision.

Its default behavior is to call get_mesh and if it returns a mesh, call the mesh ray_intersect.


bsp_object::ray_intersect_test

Prototype

virtual int ray_intersect_test(vector& ro,vector& rd,float rad=0.0f)

Parameters

Parameter | Type | Description
ro | vector& | ray origin
rd | vector& | ray_direction
rad | float | radius of collision

Return Value

Returns TRUE on any intersection, FALSE for no intersection.

Remarks

This virtual function implements the ray intersection test with the object. It should return the first collision (not necessarily closest).

Its default behavior is to call get_mesh and if a mesh is returned, it calls the mesh ray_intersect_test.


bsp_object::remove_from_bsp

Prototype

void remove_from_bsp()

Parameters

None

Return Value

None

Remarks

This function removes the object from the bsp tree, by removing it from the linked list of elements from the bsp_node the object is in. After removing the object from the bsp tree, you can move it around and reinsert it in a new position.


bsp_object::step

Prototype

virtual int step(int dt)

Parameters

Parameter | Type | Description
dt | int | time interval in ms from last frame

Return Value

If it returns TRUE, the object is repositioned in bsp tree, returns FALSE if the object does not move.

Remarks

This virtual function is used for updating the object. The object must do whatever it has to do for the elapsed time interval (move, rotate, attack, ... whatever).

Its default behaviour is to move like a particle if not implemented by a sub-class.


class class_desc

Definition

class class_desc
{
public:
virtual void *create()=0;
virtual char *get_name()=0;
virtual int get_type()=0;
};

Data Members

None

Methods

create, get_name, get_type

Remarks

This class holds the description for the classes defined in Fly3D plug-ins. Each Fly3D plug-in will enumerate a fixed number of instances to this class and each will represent a game object. Its virtual functions are used to create and get information about the plug-in object class.

See Also

param_desc, flydll, flydllgroup


class_desc::create

Prototype

virtual void *create()

Parameters

None

Return Value

Returns the pointer to the newly allocated class.

Remarks

This function creates a new instance of the described Fly3D plug-in object class. It allocates the new instance using the new operator and should be freed with the delete operator when not in use anymore.


class_desc::get_name

Prototype

virtual char *get_name()

Parameters

None

Return Value

Returns a pointer to the name of the class being described.

Remarks

This function is used to get the name of the described class.


class_desc::get_type

Prototype

virtual int get_type()

Parameters

None

Return Value

Returns the described class type id.

Remarks

This function is used to get the class id of the described Fly3D plug-in object class. Each Fly3D plug-in object must have an unique integer identifier.


class console

Definition

class console
{
public:

int mode,time,nlines,linecount,winlines;
char *buf[CONSOLE_MAX_LINES];

char cmd_line[256];
int cmd_pos;

float dx,dy;

console();
~console();

void show();
void hide();
void draw();
void step(int dt);
float draw_text(float x,float y,char *text);

void key_press(int key);
void add_string(char *fmt, ...);
int command_tokens(char *str,char **token);
void command_exec(char *str);
};

Data Members

Member | Type | Description
mode | int | console flags: (1 closing, 0 closed, 1 opening)
time | int | current animation time
nlines | int | number of lines in buf
linecount | int | current line number
winlines | int | number of lines currently visible
buf | char [] | the console string history
cmdline | char [] | the current command line
cmd_pos | int | the current command line cursor position
dx | float | cursor size in x
dy | float | cursor size in y

Methods

show, hide, draw, step, draw_text, key_press, add_string, command_tokens, command_exec

Remarks

This class implements the graphical game console. It enables you to type commands and execute them. Commands can create and delete game objects, change game object parameters, change current map and even save the current level state.

See Also

flyEngine


console::add_string

Prototype

void add_string(char *fmt, ...)

Parameters

Parameter | Type | Description
fmt | char * | string format and parameters

Return Value

None

Remarks

This function adds a new string to the console history. It uses the printf syntax, so you can add formatted strings.


console::command_exec

Prototype

void command_exec(char *str)

Parameters

Parameter | Type | Description
str | char * | string to execute

Return Value

None

Remarks

This function executes a console command.


console::command_tokens

Prototype

int command_tokens(char *str,char **token)

Parameters

Parameter | Type | Description
str | char * | string to be processed
token | char ** | string tokens

Return Value

Returns the number of tokens found in the string.

Remarks

This function converts a string into tokens (fragments the string at its spaces).


console::draw

Prototype

void draw()

Parameters

None

Return Value

None

Remarks

Draws the console with its current number of lines and all text currently visible.


console::draw_text

Prototype

float draw_text(float x,float y,char *text)

Parameters

Parameter | Type | Description
x | float | position of text in x
y | float | position of text in y
text | char * | the text string

Return Value

Returns the x position at the end of the printed text.

Remarks

This function draws a string of text in the console.


console::hide

Prototype

void hide()

Parameters

None

Return Value

None

Remarks

This function closes the console. The number of lines in the colsole will decrease to 0 and the console will be closed.


console::key_press

Prototype

void key_press(int key)

Parameters

Parameter | Type | Description
key | int | pressed key code

Return Value

None

Remarks

This function handles keyboard input to the console. It must be called with all pressed keys when console is on.


console::show

Prototype

void show()

Parameters

None

Return Value

None

Remarks

This function tells the console to open. The number of lines in the console will start growing until it takes up 1/3 of the screen.


console::step

Prototype

void step(int dt)

Parameters

Parameter | Type | Description
dt | int | elapsed time is ms

Return Value

None

Remarks

This function manages the animating of the console (opening and closing). It must be called every frame with the elapsed time for the console to open/close properly.


class directX

Definition

class directX
{
public:
int mpmode;
int nplayers;
player_data players[FLYMP_MAXPLAYERS];
unsigned char diks[256];
DIMOUSESTATE dims;

directX(HWND hWnd,HINSTANCE hInst)
{ memset(this,0,sizeof(directX)); Init(hWnd,hInst); };

void get_input();
int load_wav_file(LONG cchBuffer,HPSTR pchBuffer,LPDIRECTSOUNDBUFFER *buf,LPDIRECTSOUND3DBUFFER *buf3d);
void set_listener(float *pos,float *vel,float *Y,float *Z);
LPDIRECTSOUNDBUFFER clone_sound(LPDIRECTSOUNDBUFFER buf);
void set_master_volume(int volume);
int init_multiplayer(char *netaddress=0);
void free_multiplayer();
mp_games *enum_games(LPGUID app_guid);
int join_game(LPGUID game_guid,char *player_name);
int create_game(LPGUID app_guid,char *game_name);
char *get_player_address(DWORD dpid);
void send_message(mp_msg *msg,int len,DWORD dpid=0);
int get_num_messages();
mp_msg *get_message(DWORD *size);
int add_player(char *name,DWORD dpid,void *data);
void *remove_player(int i);

~directX()
{ Release(); };
};

Data Members

Member | Type | Description
mpmode | int | current multiplayer mode. one of the following enumerated types: FLYMP_NOMP - no multiplayer FLYMP_CLIENT - running as client FLYMP_SERVER - running as server
nplayers | int | number of players in a multiplayer game
players | player_data[] | player data array
diks | unsigned char[] | direct input keys array
dims | DIMOUSESTATE | direct input mouse state

Methods

get_input, load_wav_file, set_listener, clone_sound, set_master_volume, init_multiplayer, free_multiplayer, enum_games, join_game, create_game, get_player_address, send_message, get_num_messages, get_message, add_player, remove_player

Remarks

This class implements an interface with DirectX for input, sound and multiplayer.
A global variable named directx is the main interface with this class and must be initialized/freed with the init_directx and close_directx global functions.

See Also

Global Variables, Global Functions, mp_games, mp_msg


directX::add_player

Prototype

int add_player(char *name,DWORD dpid,void *data)

Parameters

Parameter | Type | Description
name | char * | player name
dpid | DWORD | directplay player id
data | void * | pointer to specific player data

Return Value

Returns the player index into the players array for the added player, and -1 if player could not be added.

Remarks

This function adds a new player to the current game.


directX::clone_sound

Prototype

LPDIRECTSOUNDBUFFER clone_sound(LPDIRECTSOUNDBUFFER buf)

Parameters

Parameter | Type | Description
buf | LPDIRECTSOUNDBUFFER | destination buffer for cloned sound

Return Value

Returns the DirectX sound buffer pointer for the cloned sound.

Remarks

This function clones a sound buffer. Used for playing simultaneous instances of the same sound.


directX::create_game

Prototype

int create_game(LPGUID app_guid,char *game_name)

Parameters

Parameter | Type | Description
app_guid | LPGUID | IP address of server when starting a client. NULL for starting a server.
game_name | char * | game name

Return Value

Returns TRUE is game creation is OK, FALSE if creation failed.

Remarks

This function creates a new multiplayer game. It must be called from a server application and other clients will be able to join.


directX::enum_games

Prototype

mp_games *enum_games(LPGUID app_guid)

Parameters

Parameter | Type | Description
app_guid | LPGUID | application GUID. use FLYGUID for Fly3D games.

Return Value

Returns pointer to the game's description class.

Remarks

Returns information on all games running on the selected server.
It is used for enumerating available games to join on a specific server.


directX::free_multiplayer

Prototype

void free_multiplayer()

Parameters

None

Return Value

None

Remarks

Frees the TCP/IP connection used in multiplayer games. It must be called when closing a server or a client that was playing a multiplayer game.


directX::get_input

Prototype

void get_input()

Parameters

None

Return Value

None

Remarks

This function gets the current key and mouse state. It fills the diks array with all current keyboard key states and the dims array with the current mouse state. It is required once a frame.


directX::get_message

Prototype

mp_msg *get_message(DWORD *size)

Parameters

Parameter | Type | Description
size | DWORD * | pointer to a DWROD to receive message size

Return Value

Returns the message pointer.

Remarks

This function retrieves the first message in the application message queue. The size parameter will be filled with the actual size of the message.


directX::get_num_messages

Prototype

int get_num_messages()

Parameters

None

Return Value

Returns the number of messages available in the message queue.

Remarks

You must call get_message as many times as the value returned by this function to clear the message queue.


directX::get_player_address

Prototype

char *get_player_address(DWORD dpid)

Parameters

Parameter | Type | Description
dpid | DWORD | directplay player id

Return Value

Returns the IP address string for specified player.

Remarks

This function is used to query the IP addres of one of the players in the current game.


directX::init_multiplayer

Prototype

int init_multiplayer(char *netaddress=0)

Parameters

Parameter | Type | Description
netaddress | char * | IP address of server when starting a client. NULL for starting a server.

Return Value

Returns TRUE if initialization is OK (TCP/IP installed), FALSE if unable to initialize multiplayer.

Remarks

This function starts multiplayer mode by initializing TCP/IP. It must be called before creating servers or connecting to a game.
It should be called with netaddress=NULL for creating a server.
When creating a client, set netaddress to the server address from where the games will be enumerated from.


directX::join_game

Prototype

int join_game(LPGUID game_guid,char *player_name)

Parameters

Parameter | Type | Description
game_guid | LPGUID | game GUID to join
player_name | char * | player name

Return Value

Returns the DirectPlay player id if game join is OK, 0 if unable to join.

Remarks

This function joins a multiplayer game. It must be called with one of the games enumerated by the enum_games function.


directX::load_wav_file

Prototype

int load_wav_file(LONG cchBuffer,HPSTR pchBuffer,LPDIRECTSOUNDBUFFER *buf,LPDIRECTSOUND3DBUFFER *buf3d)

Parameters

Parameter | Type | Description
cchBuffer | LONG | .wav file size in bytes
pchBuffer | HPSTR | .wav file bytes
buf | DIRECTSOUNDBUFFER ** | destination direct sound buffer
buf3d | DIRECTSOUND3DBUFFER ** | destination direct sound buffer 3D

Return Value

Returns TRUE if loading is OK, FALSE on any error.

Remarks

Loads a .wav file stored in memory. It creates the direct sound buffer (*buf and *buf3d) to receive the sound. Note that the buf and buf3d parameters are pointers to pointers.


directX::remove_player

Prototype

void *remove_player(int i)

Parameters

Parameter | Type | Description
i | int | player index

Return Value

Returns the data associated with the player when the player was created.

Remarks

This function removes a player from the game. The parameter i must be the index of the player in the players array.


directX::send_message

Prototype

void send_message(mp_msg *msg,int len,DWORD dpid=0)

Parameters

Parameter | Type | Description
msg | mp_msg * | message to send
len | int | length in bytes of message
dpid | DWORD | player to send message to: 0 - all players <>0 - player id of destination player

Return Value

None

Remarks

This function sends a multiplayer message. The message can have any size, but you must keep it as small as possible for a better performance. The message header must be as a mp_msg struct.


directX::set_listener

Prototype

void set_listener(float *pos,float *vel,float *Y,float *Z)

Parameters

Parameter | Type | Description
pos | float * | the listener position (pointer to 3 floats)
vel | float * | the listener velocity (pointer to 3 floats)
Y | float * | the listener up vector (pointer to 3 floats)
Z | float * | the listener front vector (pointer to 3 floats)

Return Value

None

Remarks

Sets current sound listener attributes. All playing sounds will be relative to the listener position, velocity and rotation. If vel is (0,0,0), no Doppler effect is used.


directX::set_master_volume

Prototype

void set_master_volume(int volume)

Parameters

Parameter | Type | Description
volume | int | volume to set (negative value). use 0 for maximum volume.

None

Remarks

Sets the master sound volume. Volume is a negative value with 0 being the maximum volume.


class face

class face : public plane

Definition

class face : public plane
{
public:
vector *vert[3];
vector edgenormal[3];
vector vertnormal[3];
vector color;
int texpic;
int lm;
float uv[3][2];
float lmuv[3][2];
float emmradius;
int lastdraw;
int indx;

int ray_intersect(vector& ro,vector& rd,vector& ip,float&
dist,float rad=0.0f);
void inverse_map(vector& p,float& u,float& v);
void forward_map(float& u,float& v,vector& p);
};

Data Members

Member | Type | Description
vert | vector*[3] | pointer to the three face vertices
edgenormal | vector[3] | the three edge normals
vertnormal | vector[3] | the three vertex normals
color | vector | the face color (r,g,b,a)
texpic | int | the face texture picture
lm | int | the face light map
uv | float[3][2] | the three vertex texture co-ordinates
lmuv | float[3][2] | the three vertex light map texture co-ordinates
emmradius | float | the face emmisive radius (if self illuminated)
lastdraw | int | the last frame in which the face was drawn
indx | int | the face index into the faces array

Methods

ray_intersect, inverse_map, forward_map

Remarks

This class implements a 3D face with three vertices. Texture and light map can be applied to the face and functions for collision detection are also implemented.

If emmradius is >0, the face will cast light when static level light computation is calculated.

See Also

vector, plane, mesh


face::forward_map

Prototype

void forward_map(float& u,float& v,vector& p)

Parameters

Parameter | Type | Description
u | float& | point co-ordinate in u axis
v | float& | point co-ordinate in v axis
p | vector& | point in object space

Return Value

None

Remarks

This function maps a point from light map texture space into object space.
The (u,v) pair define a point in the object's light map texture space that can be mapped into an object space 3D point.
This is used to find where a light map pixel is in scene co-ordinates.


face::inverse_map

Prototype

void inverse_map(vector& p,float& u,float& v)

Parameters

Parameter | Type | Description
p | vector& | point in object space
u | float& | point co-ordinate in u axis
v | float& | point co-ordinate in v axis

Return Value

None

Remarks

This function maps a point from object space into light map texture space.
The p parameter defines a point in the object's space that is mapped into an object light map texture space 2D point.
This is used to find which light map pixel corresponds to a point in the face surface.


face::ray_intersect

Prototype

int ray_intersect(vector& ro,vector& rd,vector& ip,float& dist,float rad=0.0f)

Parameters

Parameter | Type | Description
ro | vector& | ray origin
rd | vector& | ray direction
ip | vector& | intersection point
dist | float& | intersection distance
rad | float | intersection radius

Return Value

Returns TRUE if an intersection is found, FALSE if no intersection is found.

Remarks

This function computes the intersection with the face.
If an intersection is found, ip will be set to the intersection point, dist will be set to the distance from the ray origin (ro) to the indersection point (ip).
If rd is normalized, the dist value will be in scene units, if not, if will be the distance divided by the ray direction (rd) length.
The rad parameter sets the collision radius. If >0, the collision will be tested for a sphere with radius rad.


class fly_pak

Definition

class fly_pak
{
public:
char *buf;
unsigned long pos, len;

fly_pak();

void seek(long offset);
bool open(char *filename);
void close();
int read(void *dest, int size);
void get_profile_string(char *section, char *key, char *dest);
void get_string(char *dest);
int get_int();
float get_float();
FILE *get_fp(char *filename);

~fly_pak();
};

Data Members

Member | Type | Description
buf | char * | file buffer
pos | unsigned long | position inside buffer
len | unsigned long | length of buffer

Methods

seek, open, close, read, get_profile_string, get_string, get_int, get_float, get_fp

Remarks

This class implements the loading of files. It should be used as it can read standalone files or files included in .fpk packages. The .fpk file is a group of files that are packed into a single file. When opening a file, first it tries to open the standalone file, and if it fails to find the file, it looks up the file path for a .fpk file that could contain the desired file.

See Also

flypakutil


fly_pak::close

Prototype

void close()

Parameters

None

Return Value

None

Remarks

Closes an already opened file.


fly_pak::get_float

Prototype

float get_float()

Parameters

None

Return Value

Returns a float loaded from the opened file.

Remarks

This function reads a float from the opened file. It is just like doing a fscanf(fp,"%f",&var).


fly_pak::get_fp

Prototype

FILE *get_fp(char *filename)

Parameters

Parameter | Type | Description
filename | char * | filename for the file to open

Return Value

Returns the FILE* for the selected file.

Remarks

This function is used to get an standard FILE* for a file in a .fpk package.


fly_pak::get_int

Prototype

int get_int()

Parameters

None

Return Value

Returns an integer loaded from the opened file.

Remarks

This function reads an integer from the opened file. It is just like doing a fscanf(fp,"%i",&var).


fly_pak::get_profile_string

Prototype

void get_profile_string(char *section, char *key, char *dest)

Parameters

Parameter | Type | Description
section | char * | section name
key | char * | key name
dest | char * | destination string

Return Value

None

Remarks

This function works just like the GetPrivateProfileString Windows API function. It is used to manage .ini type of files and as .fly files are just text .ini files, it is used to load the .fly files.


fly_pak::get_string

Prototype

void get_string(char *dest)

Parameters

Parameter | Type | Description
dest | char * | destination string

Return Value

None

Remarks

This function is used to load a string from the specified file. It works just like the fgets standard I/O function.


fly_pak::open

Prototype

bool open(char *filename)

Parameters

Parameter | Type | Description
filename | char * | filename for file to open

Return Value

Returns TRUE if open if OK, FALSE on any error.

Remarks

This function opens a file (standalone or from a .fpk package). It first tries to open the file as a standalone file. If it fails to open it, it looks up the file path for .fpk files that may contain the desired file. All open files needs to be closed using the close method.


flay_pak::read

Prototype

int read(void *dest, int size)

Parameters

Parameter | Type | Description
dest | void * | destination memory pointer
size | int | number of bytes to read

Return Value

Returns the actual number of bytes copied to the destination buffer.

Remarks

This function reads an specified number of bytes from the opened file into the dest memory buffer. If the number of bytes requested is more than the bytes available in the file, only the available bytes are copied and the number of bytes actually copied are returned.


fly_pak::seek

Prototype

void seek(long offset)

Parameters

Parameter | Type | Description
offset | long | offset to move from current position

Return Value

None

Remarks

This function seeks the current file pointer just like the fseek standard I/O function. The offset can be positive or negative.


class flypakutil

class fly_pak_util

Definition

class fly_pak_util
{
public:
bool implode(char *folder);
bool explode(char *filename);
};

Data Members

None

Methods

implode, explode

Remarks

This class uses the fly_pak class to pack/unpack complete directories.

See Also

fly_pak


fly_pak_util::explode

Prototype

bool explode(char *filename)

Parameters

Parameter | Type | Description
filename | char * | filename for the .fpk file to unpack

Return Value

Returns TRUE is unpacking was OK, FALSE on any error.

Remarks

This function unpacks a .fpk file creating all files and directories included in it.


fly_pak_util::implode

Prototype

bool implode(char *folder)

Parameters

Parameter | Type | Description
folder | char * | folder to pack

Return Value

Returns TRUE is packing was OK, FALSE on any error.

Remarks

This function packs all files from the selected folder (including subdirectories) into a single .fpk file.


class flydll

Definition

class flydll
{
public:
HINSTANCE hdll;
char dll_filename[256];
int nclasses;
int (* num_classes)();
class_desc *(* get_class_desc)(int i);
int (* fly_message)(int msg,int param,void *data);
};

Data Members

Member | Type | Description
hdll | HINSTANCE | instance handle of the plug-in dll
dll_filename | char * | file name of the plug-in dll
nclasses | int | number of classes implemented in the plug-in
numclasses | int (*)() | pointer to numclasses() function of the plug-in dll
get_class_desc | class_desc *(*)(int i) | pointer to get_class_desc() function of the plug-in dll
fly_message | int (*)(int msg, int param, void *data) | pointer to fly_message() function of the plug-in dll

Methods

None

Remarks

This class holds information for each Fly3D plug-in dll, including the number of classes implemented in the dll, and the pointers to the dll exported functions.

See Also

class_desc, param_desc, flydllgroup


class flydllgroup

Definition

class flydllgroup
{
public:
int ndll;
flydll **dll;
int ncd;
class_desc **cd;

flydllgroup();

void reset();
int add_dll(char *filename);
int delete_dll(char *filename);
void move_dll(char *filename,int newrelpos);
int send_message(int msg,int param,void *data);
void load_all_classes(fly_pak *file);
void load_classes(int d,fly_pak *file);
void load_default_param(bsp_object *o,char *sec,fly_pak *file);
void delete_class(bsp_object *o);
void delete_references(bsp_object *o);
bsp_object *add_class(char *name);

virtual ~flydllgroup();
};

Data Members

Member | Type | Description
ndll | int | number of Fly3D plug-in dlls in dll array
dll | flydll * | array of plug-in dll description classes
ncd | int | total number of classes implemented by the plug-ins in cd array
cd | class_desc * | array of class description classes

Methods

reset, add_dll, delete_dll, move_dll, send_message, load_all_classes, load_classes, load_default_param, delete_class, delete_references, add_class

Remarks

This class implements a group of Fly3D plug-in dlls. Each Fly3D plug-in dll can enumerate any number of bsp_object derived classes.
The plug-in dlls are stored in the dll member variable and the classes implemented by theem are stored in the cd member variable.

See Also

flydll, class_desc, param_desc


flydllgroup::add_class

Prototype

bsp_object *add_class(char *name)

Parameters

Parameter | Type | Description
name | char * | object class name to create an instance

Return Value

Returns an instance of the class with the specified name.

Remarks

This function is used only by the flyEditor and creates a new object from a plug-in dll by just specifying the class name.


flydll_group::add_dll

Prototype

int add_dll(char *filename)

Parameters

Parameter | Type | Description
filename | char * | filename for the Fly3D plug-in dll

Return Value

Returns TRUE if the dll was loaded OK, FALSE if not found or other error.

Remarks

This function adds a new Fly3D plug-in dll into the dll array. Its classes should them be loaded using the load_classes method.


flydllgroup::delete_class

Prototype

void delete_class(bsp_object *o)

Parameters

Parameter | Type | Description
o | bsp_object * | object to be deleted

Return Value

None

Remarks

This function is used only by the flyEditor and deletes a object from the scene. It also clears any other object reference to the one being deleted.


flydllgroup::delete_dll

Prototype

int delete_dll(char *filename)

Parameters

Parameter | Type | Description
filename | char * | filename for the Fly3D plug-in dll

Return Value

Returns TRUE if the dll was removed OK, FALSE if not found or other error.

Remarks

This function removes a Fly3D plug-in dll from memory. It removes all classes implemented by the dll from memory and frees resources associated with the dll.


flydllgroup::delete_references

Prototype

void delete_references(bsp_object *o)

Parameters

Parameter | Type | Description
o | bsp_object * | object whose references should be deleted

Return Value

None

Remarks

This function removes any references to the specified object. It is used before deleteing the object. All other objects that had pointers to this one will have their pointers set to NULL.


flydllgroup::load_all_classes

Prototype

void load_all_classes(fly_pak *file)

Parameters

Parameter | Type | Description
file | fly_pak * | .fly file

Return Value

None

Remarks

This function loops on all Fly3D plug-in dlls included in the suplied .fly file and loads all classes from each of them using the load_classes method.


flydllgroup::load_classes

Prototype

void load_classes(int d,fly_pak *file)

Parameters

Parameter | Type | Description
d | int | dll index into dll array
file | fly_pak * | .fly file

Return Value

None

Remarks

This function loads all classes from the specified Fly3D plug-in dll.


flydllgroup::load_default_param

Prototype

void load_default_param(bsp_object *o,char *sec,fly_pak *file)

Parameters

Parameter | Type | Description
o | bsp_object * | object to set parameters
sec | char * | section from .fly file to get parameters from
file | fly_pak * | .fly file

Return Value

None

Remarks

This function loads all default parameters (pos, vel, force, rot, life, colflag, mass, radius, bump, friction, active, latedraw) for the specified object. All bsp_object derived classes (implemented in Fly3D plug-ins) have these 12 default parameters.


flydllgroup::move_dll

Prototype

void move_dll(char *filename,int newrelpos)

Parameters

Parameter | Type | Description
filename | char * | filename for the Fly3D plug-in dll
newrelpos | int | relative move

Return Value

Returns TRUE if the dll was moved OK, FALSE if not found or other error.

Remarks

This function changes a Fly3D plug-in dll position (order) in the plug-in list. The order of plug-ins is important as the first ones will render first. The panorama.dll plug-in is usually the first (because it draws the background).


flydllgroup::reset

Prototype

void reset()

Parameters

None

Return value

None

Remarks

This function resets the class by freeing all allocated data.


flydllgroup::send_message

Prototype

int send_message(int msg,int param,void *data)

Parameters

Parameter | Type | Description
msg | int | message id
param | int | general parameter
data | void * | general data pointer

Return Value

Returns a value from the plug-in dlls (0 if passed on all plug-in dlls, <>0 if some plug-in stoped message by returning <>0)

Remarks

This function is used to send messages to the plug-in dlls. It will send the message to all plug-in dlls included in flydllgroup class. The data pointer can be used to send pointers to any type/size of data as all messages are local.
The send_message function will loop throught all plug-in dlls loaded, and for each one, if the plug-in dll returns 0, message passes to the next plug-in dll in the list, if it return <>0, the send_message function stops and returns the value. So if return value is zero, it passed on all plug-in dlls.


class flyEngine

Definition

class flyEngine
{
public:

int cur_step,cur_step_base;
int cur_frame,cur_frame_base;
int cur_time,cur_dt;

flydllgroup dll;
console con;

bsp_object *player;
bsp_object *cam;
vector frustum[5];

bsp_object *excludecollision,*stepobj;
bsp_object *elemdraw[MAX_ELEMDRAW];
bsp_object *elemlatedraw[MAX_ELEMDRAW];

int nelemdraw;
bsp_object *elemdraw[MAX_ELEMDRAW];
int nelemlatedraw[MAX_LATEDRAW_LAYERS];
bsp_object *elemlatedraw[MAX_LATEDRAW_LAYERS][MAX_ELEMDRAW];
int *facedraw;
int nfacedraw;
int *facedrawtransp;
int nfacedrawtransp;

char flysdkpath[256];
char flyfile[256];
char flydatapath[256];
char flyfilename[256];
char bspfile[256];
char status_msg[256];
char console_command[256];
unsigned status_msg_time;

float bboxdiag,viewmaxdist,viewmindist,camangle,
aspect,geomdetail,curveerr,lmpxsize,detailtile,
cartoonwidth,shadowdepth;

vector bbox1,bbox2,bboxC,filter,background,
cartooncolor,shadowcolor;

int nodedrawcount,nodeonly,pvsoff,fog,mpdelay,
antialias,amblight,mapmode,multitexture,shadows,
noinput,wireframe,mute,clearbk,moving,appid,mouse,
crosshairpic,crosshairsize,intropic,introtime,
detailpic,hwlights,stencil,cartoonpic,cartoonpicbsp;

bsp_object *active_obj0,*last_active_obj;
bsp_object *stock_obj0;
mesh *model_obj0;
sound *sound_obj0;
bezier_curve *bezier_curve0;
bezier_patch *bezier_patch0;
bsp_object *shadow_obj;
bsp_object *hitobj;
mesh *hitmesh;
int hitface;
vector hitip;
int status,fontspic,fonts_width[64],consolepic;
vector *vert,*vertcolor,*vertnormal;
face *faces;
int nvert,nfaces;
int *edges,nedges,*faceedges;
bsp_node *bsp;

light_map *lm[MAX_LIGHTMAP];
light_map_pic *lmpic[MAX_LIGHTMAP];
int nlm,lmbase,nlmpic;

light_map *fm[MAX_LIGHTMAP];
light_map_pic *fmpic[MAX_LIGHTMAP];
int fmbase;

picture *piclib[MAX_PICTURES];
int npiclib;

char *pvs;
bsp_node *leaf[MAX_LEAF];
int nleaf,pvssize,pvsrowsize;

flyEngine();

void draw_bsp(int mode=0);
void draw_bsp_edges();
int collision_bsp(bsp_node *n,vector& p1,vector& p2,int elemtype=0,float
  rad=0.0f);
int collision_test(bsp_node *n,vector& p1,vector& p2,int elemtype=0,float
  rad=0.0f);
void step(int dt);
int step();
void apply_bsp(bsp_node *n,vector& p,float rad,void *data,void (*func)(void
  *data,bsp_object *e));
void apply_bsp(bsp_node *n,vector *p,int np,void *data,void (*func)(void *data,bsp_object *e));
void send_bsp_message(bsp_node *n,vector& p,float rad,int msg,int
  param,void *data);
int open_fly_file(char *file);
void close_fly_file();
int save_fly_file(char *file);
int add_lightmap(int sx,int sy);
void init_texture_cache();
void close_texture_cache();
void start_text_mode();
void end_text_mode();
void draw_text(int x,int y,char *text);
void draw_text_center(int x,int y,char *text);
virtual void set_status_msg(char *fmt, ...);
int get_picture(char *file);
bsp_object *get_stock_object(char *name);
bsp_object *get_active_object(char *name);
mesh *get_model_object(char *name);
sound *get_sound_object(char *name);
bezier_curve *get_bezier_curve(char *name);
bezier_patch *get_bezier_patch(char *name);
bsp_object *get_next_stock_object(bsp_object *o,int type=0);
bsp_object *get_next_active_object(bsp_object *o,int type=0);
int set_obj_param(char *objname,char *param,char *value);
int get_obj_param(char *objname,char *param,char *value);
int set_global_param(char *name, char *value);
int get_global_param_desc(int i,param_desc *pd);
void activate(bsp_object *d,int flag=1);
void set_camera(bsp_object *d);
bsp_node *get_random_point(vector& v,float mindist);
bsp_node *find_node(bsp_node *n,vector& v,float mindist);
int join_multiplayer(HWND hWnd,HINSTANCE hInst);
void close_multiplayer();
void check_multiplayer();

virtual ~flyEngine()
{ close_fly_file(); };
};

Data Members

Member | Type | Description
cur_step | int | current step (each call to each object step function from each frame has an unique id)
cur_step_base | int | current step base (first step id for current frame)
cur_frame | int | current frame
cur_frame_base | int | current frame base (multiple renders are possible in different viewports)
cur_time | int | current time in ms
cur_dt | int | current elapsed time from last frame in ms
dll | flydllgroup | all Fly3D plug-in dlls in current scene
con | console | console interface
player | bsp_object * | current player bsp_object pointer
cam | bsp_object * | current camera bsp_object pointer
frustum | vector[] | the view frustum (an array of 5 3D points)
excludecollision | bsp_object * | object pointer to be excluded from collision
stepobj | bsp_object * | pointer to object if inside some object step function
elemdraw | bsp_object *[] | array of elements to draw on current render
elemlatedraw | bsp_object *[][] | array of elements to draw later on current render
nelemdraw | int | number of elements in elemdraw array
nelemlatedraw | int[] | number of elements in each elemlatedraw array
facedraw | int * | array of bsp faces to draw on current render
nfacedraw | int | number of faces in facedraw array
facedrawtransp | int * | array of transparent bsp faces to draw on current render
nfacedrawtransp | int | number of faces in facedrawtransp array
flysdkpath | char [] | path for the flysdk dir
flyfile | char [] | path for the current .fly file
flydatapath | char [] | path for current .fly file data dir
flyfilename | char [] | filename for the current .fly file
bspfile | char [] | bsp filename fro the current .fly file
status_msg | char [] | the current status string
status_msg_time | unsigned | the time of the status string message
console_command | char [] | console command string, if <>"" command will be executed on next frame
viewmaxdist | float | near plane distance
viewmindist | float | far plane distance
camangle | float | camera angle in degrees
aspect | float | render view aspect ratio
geomdetail | float | geometry detail (objects subdivide maintaining a vertex distance < geomdetail)
curveerr | float | curve subdivision maximum error (curves subdivide maintaining this maximum error)
lmpxsize | float | desired size in scene units for the light map pixels (for the flyLight precomputation)
bboxdiag | float | scene bounding box diagonal
bbox1 | vector | scene bounding box minimum point
bbox2 | vector | scene bounding box maximum point
bboxC | vector | scene bounding box center
filter | vector | current screen filter color (draw over the hole screen)
background | vector | background clear color
nodedrawcount | int | number of nodes drawn in last frame
status | int | if TRUE, status is draw
nodeonly | int | if TRUE, only the node containing the camera will be drawn
pvsoff | int | if TRUE, disables pvs culling
fog | int | if TRUE, enables distance vertex fog
mpdelay | int | delay between multiplayer positional updates in ms (50 for 20 updates/sec)
antialias | int | if TRUE enables hardware antialias
amblight | int | ambient light (0-255) for the flyLight precomputation
mapmode | int | map mode as bit array of 4 bits (0-15): bit 1 - texture map bit 2 - detail map bit 3 - light map bit 4 - fog map ex. mapmode=1 means only texture map mapmode=5 means texture map and light map mapmode=15 means all maps
multitexture | int | if TRUE, enables multitexture support (up to 4 units)
shadows | int | if TRUE, enables dynamic shadows
shadowdepth | float | max distance for shadow
shadowcolor | vector | color for shadow polyons
noinput | int | if TRUE, all input is disabled (keyboard and mouse)
wireframe | int | if TRUE, renders to wireframe
mute | int | if TRUE, no sound is played
clearbk | int | if TRUE, clears the screen background prior to render
moving | int | if TRUE, some object is moving
cartoonpicbsp | int | 1D picture for bsp cartoon texture
cartoonpic | int | 1D picture for cartoon texture
cartooncolor | vector | color for cartoon edges
cartoonwidth | float | cartoon edges width
crosshairpic | int | picture for the cross-hair
crosshairsize | int | size for the cross-hair in pixels
appid | int | frontend application id
mouse | int | if TRUE, shows mouse cursor
hwlights | int | if TRUE, enable dynamic hardware lights for the dynamic objects
stencil | int | if TRUE, enables stencil buffer
datailpic | int | picture used for detail texture
detailtile | float | tile to multiply texture co-ordinates for the detail textures
active_obj0 | bsp_object * | active objects linked list
last_active_obj | bsp_object * | last object in active object linked list
stock_obj0 | bsp_object * | stock objects linked list
model_obj0 | mesh * | linked list of models
sound_obj0 | sound * | linked list of sounds
bezier_curve0 | bezier_curve * | linked list of Bezier curves
bezier_patch0 | bezier_patch * | linked list of Bezier paches
shadow_obj | bsp_object * | current object to cast shadows
hitobj | bsp_object * | current ray intersected object
hitmesh | mesh * | current ray intersected mesh
hitface | int | current ray intersected face
hitip | vector | current ray intersected point
fontspic | int | picture with the character fonts
fonts_width | int [] | array with each font character width (for fonts not fixed size)
consolepic | int | picture used on the console background
intropic | int | picture used for opening level introduction
introtime | int | time in ms for the introduction animation
nvert | int | number of vertices in bsp tree vert array
vert | vector * | array of vertices for the bsp tree faces
vertcolor | vector * | array of vertex colors for the bsp tree vertices
vertnormal | vector * | array of vertex normals
nfaces | int | number of faces in bsp tree
faces | face * | array of bsp tree faces
edges | int * | array of bsp face edges (4*nedges*sizeof(int))
nedges | int | number of edges in bsp edges array
faceedges | int * | array of edges for each bsp face (3*nfaces*sizeof(int))
bsp | bsp_node * | the bsp tree root node
lm | light_map * | individual light maps (each light mapped face points to one of these)
lmpic | light_map_pic * | light map picture groups array (each light map points to one of these)
nlm | int | number of light_map classes in lm array
lmbase | int | offset into texture array for the light map pictures
nlmpic | int | number of light_map_pic classes in lmpic array
fm | light_map * | individual fog maps
fmpic | light_map_pic * | fog map picture groups array (each fog_map points to one of these)
fmbase | int | offset into texture array for the fog maps
piclib | picture * | array of pictures used as texture maps
npiclib | int | number of pictures in piclib array
leaf | bsp_node * | bsp tree leaf array
nleaf | int | number of leaves in bsp tree
pvssize | int | size of the pvs array in bytes
pvsrowsize | int | size of each pvs row in bytes
pvs | char * | pvs bit array

Methods

collision_bsp, collision_test, step, apply_bsp, send_bsp_message, open_fly_file, close_fly_file, save_fly_file, add_light_map, init_texture_cache, close_texture_cache, start_text_mode, end_text_mode, draw_bsp, draw_bsp_edges, draw_text, draw_text_center, set_status_msg, get_picture, get_stock_object, get_active_object, get_model_object, get_sound_object, get_bezier_curve, get_bezier_patch, get_next_stock_object, get_next_active_object, set_obj_param, get_obj_param, set_global_param, get_global_param_desc, activate, set_camera, get_random_point, find_node, join_multiplayer, close_multiplayer, check_multiplayer

Remarks

This is the main interface with the engine. The global varible flyengine is initialized by the frontend and is from where all calls to the engine must be directed.

See Also

vector, console, face, base_object, mesh, bezier_curve, bezier_patch, sound, bsp_node, bsp_object, light_map, light_map_pic, flydllgroup, picture


flyEngine::activate

Prototype

void activate(bsp_object *d,int flag=1)

Parameters

Parameter | Type | Description
d | bsp_object * | stock object to activate
flag | int | flag: 1-adds to bsp 0-not add to bsp

Return Value

None

Remarks

This function activates an object from the stock. It clones the stock object and adds it to the list of active objects. If flag is TRUE, the object is also added to the bsp tree.


flyEngine::add_light_map

Prototype

int add_lightmap(int sx,int sy)

Parameters

Parameter | Type | Description
sx | int | x light map size (power of 2)
sy | int | y light map size (power of 2

Return Value

Return the light map index into the light map array for the newly cretated light map.

Remarks

This function is used add a new light map to the light map array. Dynamic objects that can use light maps use this function to allocate its light map image.


flyEngine::apply_bsp

Prototype

void apply_bsp(bsp_node *n,vector& p,float rad,void *data,void (*func)(void *data,bsp_object *e))
void apply_bsp(bsp_node *n,vector *p,int np,void *data,void (*func)(void *data,bsp_object *e));

Parameters

Parameter | Type | Description
n | bsp_node * | bsp root node
p | vector& | point
p | vector * | array of points defining a volume
np | int | number of points in p array
rad | float | radius
data | void * | general pointer data
func | void (*)(void *data,bsp_object *e) | call-back function

Return Value

None

Remarks

This function is used select objects inside a region. The call-back function will be called for every plug-in object (bsp_object derived) inside the region defined by the parameters. It is used by homing missiles, enemies and any object that needs to look around it. Even the fog maps use this function to easily select the faces it should apply the fog to.

The region can be defiend using a sphere of influence (p and rad) or a set of points (5 an define a frustum, 8 a box, etc...).


flyEngine::check_multiplayer

Prototype

void check_multiplayer()

Parameters

None

Return Value

None

Remarks

This function is used to process multiplayer messages. When connected to a multiplayer game, the function should be called every frame. It will get all the messages in the message queue and process them. System messages are processed and game messages are passed on to the plug-ins. This function is already called by the flyEngine step function if the multiplayer mode is on.


flyEngine::close_fly_file

Prototype

void close_fly_file()

Parameters

None

Return Value

None

Remarks

This function closes the current loaded level, freeing all level data (models, textures, bsp, souds, etc...).


flyEngine::close_multiplayer

Prototype

void close_multiplayer()

Parameters

None

Return Value

None

Remarks

Closes multiplayer mode removing the player from the server it is connected to. Join a game with the join_multiplayer function.


flyEngine::close_texture_cache

Prototype

void close_texture_cache()

Parameters

None

Return Value

None

Remarks

This function frees the texture manager by freeing all texture maps, light maps and fog maps from the texture hardware. It deletes the tc global variable and sets it to NULL.


flyEngine::collision_test

Prototype

int collision_test(bsp_node *n,vector& p1,vector& p2,int elemtype=0,float rad=0.0f)

Parameters

Parameter | Type | Description
n | bsp_node * | bsp root node
p1 | vector& | first point
p2 | vector& | secont point
elemtype | int | object type modifier
rad | float | collision radius

Return Value

Returns TRUE if a collision is found, FALSE if no collision is found.

Remarks

This function is used for collision detection between p1 and p2. It returns the first collision from p1 to p2 and is faster than the collision_bsp function.


flyEngine::collision_bsp

Prototype

int collision_bsp(bsp_node *n,vector& p1,vector& p2,int elemtype=0,float rad=0.0f)

Parameters

Parameter | Type | Description
n | bsp_node * | bsp root node
p1 | vector& | first point
p2 | vector& | secont point
elemtype | int | object type modifier
rad | float | collision radius

Return Value

Returns TRUE if a collision is found, FALSE if no collision is found.

Remarks

This function is used for collision detection between p1 and p2. It finds the closest collision from p1 to p2 and return the collision information in the following flyEngine members:

bsp_object *hitobj; // object pointer
mesh *hitmesh; // mesh pointer
int hitface; // face index into mesh
vector hitip; // intersected point in face

A faster version of this function is the collision_test function that returns the first collision from p1 to p2.


flyEngine::draw_bsp

Prototype

void draw_bsp(int mode)

Parameters

Parameter | Type | Description
mode | int | drawing mode: 0 - standard 1 - cartoon

Return Value

None

Remarks

This function recureses the bsp tree and select all bsp faces and dynamic object that are inside the current view frustum. Then, all faces from the bsp are drawn followed by all dynamic objects. Transparent faces and draw after the nontransparent ones and dynamic objects set to latedraw will be the last ones to render.

If cartoon mode is set, the bsp faces are drawn with the current cartoonpicbsp and then all edges from the bsp faces selected for drawing will be tested for outline by the current camera. If edge is found to be at a backface/frontface pair, the edge is draw as a black line.


flyEngine::draw_bsp_edges

flyEngine::draw_bsp_egdes

Prototype

void draw_bsp_edges()

Parameters

None

Return Value

None

Remarks

This function draws the edges (outlines) for the selected bsp faces. It is used by caroton like bsp renders.
The current cartoonpicwidth and cartooncolor flyEngine class variables are used and define the width of the lines and their color.


flyEngine::draw_text

Prototype

void draw_text(int x,int y,char *text)

Parameters

Parameter | Type | Description
x | int | x screen coordinate for text
y | int | y screen coordinate for text
text | char * | text string

Return Value

None

Remarks

This function draws a string of text at the specified screen co-ordinates. The text is drawn as a set of texture mapped faces using the selected font texture in flyEngine fontspic member variable. Before using this function, text mode must be started using the start_text_mode function.


flyEngine::draw_text_center

Prototype

void draw_text_center(int x,int y,char *text)

Parameters

Parameter | Type | Description
x | int | x screen coordinate for text
y | int | y screen coordinate for text
text | char * | text string

Return Value

None

Remarks

This function draws a string of text centred at the specified screen co-ordinates. The text is drawn as a set of texture mapped faces using the selected font texture in flyEngine fontspic member variable. Before using this function, text mode must be started using the start_text_mode function.


flyEngine::end_text_mode

Prototype

void end_text_mode()

Parameters

None

Return Value

None

Remarks

This function ends text mode and restores the camera to a perspective camera at the object selected from the flyEngine member variable cam. Start text mode using the start_text_mode function.


flyEngine::find_node

Prototype

bsp_node *find_node(bsp_node *n,vector& v,float mindist)

Parameters

Parameter | Type | Description
n | bsp_node * | bsp root node
v | vector& | point in world co-ordinates
mindist | float | minimum distance

Return Value

Returns the bsp leaf the point v is in.

Remarks

This function finds the leaf node for a given point. If the point distance to any plane is less than mindist, then the leaf is rejected.


flyEngine::get_active_object

Prototype

bsp_object *get_active_object(char *name)

Parameters

Parameter | Type | Description
name | char * | object name

Return Value

Returns a pointer to the given object or NULL if object not found.

Remarks

This function is used to get objects from the active objects linked list. It returns the object pointer for a given string based name.


flyEngine::get_bezier_curve

Prototype

bezier_curve *get_bezier_curve(char *name)

Parameters

Parameter | Type | Description
name | char * | curve name

Return Value

Returns a pointer to the given Bezier curve or NULL if curve not found.

Remarks

This function is used to get curves from the stock. It returns the curve pointer for a given string based curve name. If curve is not in the curve linked list, it attempts to load the curve from disk.


flyEngine::get_bezier_patch

Prototype

bezier_patch *get_bezier_patch(char *name)

Parameters

Parameter | Type | Description
name | char * | patch name

Return Value

Returns a pointer to the given patch or NULL if patch not found.

Remarks

This function is used to get patches from the stock. It returns the patch pointer for a given string based patch name. If patch is not in the patch linked list, it attempts to load the patch from disk.


flyEngine::get_global_param_desc

Prototype

int get_global_param_desc(int i,param_desc *pd)

Parameters

Parameter | Type | Description
i | int | global parameter index
pd | param_desc * | pointer to param_desc to be filled

Return Value

Returns the number of global parameters if called with pd=NULL

Remarks

This function is used to get the parameter description for any of the global flyEngine parameters.


flyEngine::get_model_object

Prototype

mesh *get_model_object(char *name)

Parameters

Parameter | Type | Description
name | char * | model name

Return Value

Returns a pointer to the given model or NULL if model not found.

Remarks

This function is used to get models from the stock. It returns the model pointer for a given string based name. Models can be .3ds or .fao files. If model is not in the model linked list, it attempts to load the model from disk.


flyEngine::get_next_active_object

Prototype

bsp_object *get_next_active_object(bsp_object *o,int type=0)

Parameters

Parameter | Type | Description
o | bsp_object * | object pointer
type | int | object type modifier

Return Value

Returns the object next to the specified one or NULL if at end of list.

Remarks

This function is used to walk through the active object linked list. When called with o=NULL it will return the first object in the active objects linked list. When called with o<>NULL it will return the object following the object o in the active objects linked list. If the type parameter is <>0, only objects with that type id are returned.

Usually used like this:

bsp_object *obj=0;
while( obj=flyengine->get_next_active_object(obj) )
{
// do somethig with object obj
}


flyEngine::get_next_stock_object

Prototype

bsp_object *get_next_stock_object(bsp_object *o,int type=0)

Parameters

Parameter | Type | Description
o | bsp_object * | object pointer
type | int | object type modifier

Return Value

Returns the object next to the specified one or NULL if at end of list.

Remarks

This function is used to walk through the stock object linked list. When called with o=NULL it will return the first object in the stock objects linked list. When called with o<>NULL it will return the object following the object o in the stock objects linked list. If the type parameter is <>0, only objects with that type id are returned.

Usually used like this:

bsp_object *obj=0;
while( obj=flyengine->get_next_stock_object(obj) )
{
// do somethig with object obj
}


flyEngine::init_texture_cache

Prototype

void init_texture_cache()

Parameters

None

Return Value

None

Remarks

This function initializes the texture manager. It loads all texture maps, light maps and fog maps into the texture manager and texture hardware. After calling this function, you can access the texture manager by the textcache derived class stored in the global variable tc allocated by this function.


flyEngine::join_multiplayer

Prototype

int join_multiplayer(HWND hWnd,HINSTANCE hInst)

Parameters

Parameter | Type | Description
hWnd | HWND | frontend window handle
hInst | HINSTANCE | frontend instance handle

Return Value

Returns TRUE if a game is joined, FALSE on any error or join cancel.

Remarks

This function is used to join a multiplayer game. A dialogue is shown with the player name and it lets the user select the server and the game to join. If a game is selected for joining, it loads the level the game is running on and returns TRUE. If the level is not in the user computer or the level name is not received, it returns FALSE and the game is not joined. When leaving the game, the multiplayer mode must be closed with the close_multiplayer function.


flyEngine::open_fly_file

Prototype

int open_fly_file(char *file)

Parameters

Parameter | Type | Description
file | char * | filename for the .fly file to load

Return Value

Returns TRUE is loading is OK, FALSE on any error.

Remarks

This function loads a level from a .fly file. It loads all resources associated with the .fly file (plug-ins, objects, object parameters, textures, models, bsp, sounds, etc...).


flyEngine::save_fly_file

Prototype

int save_fly_file(char *file)

Parameters

Parameter | Type | Description
file | char * | filename for the .fly file to save

Return Value

Returns TRUE is saving is OK, FALSE on any error.

Remarks

This function saves the .fly file that represents the current loaded level. The .fly file is a .ini like text file and includes information on all plug-ins used in the level together with all objects defined in each plug-in and its parameters.


flyEngine::send_bsp_message

Prototype

void send_bsp_message(bsp_node *n,vector& p,float rad,int msg,int param,void *data)

Parameters

Parameter | Type | Description
n | bsp_node * | root bsp node
p | vector& | point
rad | float | radius
msg | int | message type
param | int | parameterr
data | void * | general pointer parameter

Return Value

None

Remarks

This function send a message to all active plug-in objects inside the sphere of influence defined by the p and rad parameters. All plug-in objects (derived from bsp_object) receive the message through their message virtual function.


flyEngine::set_camera

Prototype

void set_camera(bsp_object *d)

Parameters

Parameter | Type | Description
d | bsp_object * | camera is set to view from the object

Return Value

None

Remarks

This function is used to place the camera at a specified object. It computes the view frustum and sets the hardware projection matrix. All render calls after this function will use a camera placed at the object looking down its negative Z axis.


flyEngine::set_global_param

Prototype

int set_global_param(char *name, char *value)

Parameters

Parameter | Type | Description
name | char * | global parameter name
value | char * | string with parameter value

Return Value

Returns FALSE if parameter is not in the global parameter list, TRUE if parameter was found and value is set.

Remarks

This function is used to set a flyEngine global parameter from a string.


flyEngine::set_obj_param

Prototype

int set_obj_param(char *objname,char *param,char *value)

Parameters

Parameter | Type | Description
objname | char * | object name
param | char * | parameter name
value | char * | string to receive the parameter value

Return Value

Returns 0 if parameter was found and value is set, 1 if object not found and 2 if parameter not found.

Remarks

This function is used to set an object's parameter from a string representation of its value.


flyEngine::set_status_msg

Prototype

virtual void set_status_msg(char *fmt, ...)

Parameters

Parameter | Type | Description
fmt | char * | printf like parameter list

Return Value

None

Remarks

This function is used to print out text to the status message area. The text is added to the console and also shown for a small time at the screen status area. General game information is drawn here, for example, connected players, kills, deaths, etc... Use it just like a printf function with variable number of parameters.


flyEngine::start_text_mode

Prototype

void start_text_mode()

Parameters

None

Return Value

None

Remarks

This function starts text mode. It sets an orthographic camera and future rendering calls can use 2D vertices with screen co-ordinates. Use draw_text and draw_text center for drawing text with the current selected font in fontspic flyEngine member variable. All status and 2D game interface must be draw after starting text mode. Text mode is ended calling end_text_mode function.


flyEngine::step

Prototype

void step(int dt)
int step()

Parameters

Parameter | Type | Description
dt | int | elapsed time in ms

Return Value

Return the number of ms elapsed from last frame.

Remarks

This function is used to update the game after an elapsed time. The main loop from the frontend must call this function every frame.

If called without the elapsed time, the elapsed time from last frame is computed, the scene is updated for the computed time interval and this interval is returned.

The following order of operations is performed inside this function:

1) Get current state for mouse and keyboard
2) For all light maps changed in the last frame, restore them to the original values.
3) For all fog maps changed in the last frame, clear them.
4) For each active object in the active objects linked list:
if object life<0
delete the object
else
increment cur_step varaible
call object step function
if object step function returns true (moved), reposition it in the bsp
5) Increment cur_frame variable
6) For all light maps changed in this frame, update them to the texture manager
7) For all fog maps changed in this frame, update them to the texture manager
8) Send the FLYM_UPDATESCENE to all loaded plug-ins (some plug-ins will draw the scene here)
9) If multiplayer is on, call check_multiplayer for processing multiplayer messages.
10) If multiplayer is on and running on a client, check last player update message time and send a FLYM_MPUPDATE message to the plug-ins if the time from the last update is greater than the mpdelay variable
11) Calls the console step function


class light_map

Definition

class light_map
{
public:
vector v0, v1, v2;
vector d0, d1, d2, normal;
float det;
float uv[3][2];
int lastupdate;
int pic;
int offsetx,offsety;
int sizex,sizey;
int facenum;
unsigned char *bmp;
int bytespixel,bytesx,bytesxy;

light_map(int f,int p,int x,int y,int sx,int sy,int bp=3)
{
facenum=f;
pic=p;
offsetx=x;
offsety=y;
sizex=sx;
sizey=sy;
bytespixel=bp;
lastupdate=0;
bytesx=sx*bp;
if (bytesx&3)
bytesx+=4-(bytesx&3);
bytesxy=bytesx*sy;
bmp=new unsigned char[bytesxy];
};
void map_point(float u, float v, vector &point);
void set_base(face *f,light_map_pic *lmp,vector&
pos=vector(0,0,0));
void illum(vector& pos,vector& color,float rad,int shadows);
void load(light_map_pic *lmp);
void save(light_map_pic *lmp);

virtual ~light_map()
{
if (bmp)
delete bmp;
};
};

Data Members

Member | Type | Description
d0 | vector | light_map origin (0,0) in world space
d1 | vector | light_map u vector (1,0) in world space
d2 | vector | light_map v vector (0,1) in world space
lastupdate | int | last frame this light_map has changed
pic | int | light_map_pic index
offsetx | int | x offset into light_map_pic
offsety | int | y offset into light_map_pic
sizex | int | x size of light_map (power of 2 or not)
sizey | int | y size of light_map (power of 2 or not)
facenum | int | face index for one face using this light_map
bmp | unsigned char * | light_map bitmap
bytespixel | int | the light map bytes per pixel: 3 - RGB 4 - RGBA
bytesx | int | number of bytes per line (sizex*bytespixel aligned to 4 bytes)
bytesxy | int | total bytes of the light_map bmp (bytesx*sizey)

Methods

constructor, map_point, set_base, illum, load, save

Remarks

This class implements a light map. Several faces (co-planar) can share the same light_map and many light_maps can share the same light_map_pic. Each light_map has an offset and size inside its light_map_pic.

See Also

light_map_pic, vector, face, flyEngine


light_map constructor

Prototype

light_map(int f,int p,int x,int y,int sx,int sy,int bp=3)

Parameters

Parameter | Type | Description
f | int | face using this light map (can be -1 for non coplanar faces)
p | int | light_map_pic for the light_map
x | int | x offset into light_map_pic
y | int | y offset into light_map_pic
sx | int | x size of light_map (power of 2 or not)
sy | int | y size of light_map (power of 2 or not)
bp | int | light_map bytes per pixel: 3 - RGB (light map) 4 - RGBA (fog map)

Remarks

Creates the light map and allocates the bmp array.


light_map::illum

Prototype

void illum(vector& pos,vector& color,float rad,int shadows)

Parameters

Parameter | Type | Description
pos | vector& | light position
color | vector& | light color
rad | float | light radius
shadows | int | shadows flag: 0 - no shadows 1 - single object shadows 2 - global shadows

Return Value

None

Remarks

This function dynamicaly illuminates the light_map pixels based on the above parameters.


light_map::load

Prototype

void load(light_map_pic *lmp)

Parameters

Parameter | Type | Description
lmp | light_map_pic * | light_map_pic with original light_map values

Return Value

None

Remarks

This function restores the light_map pixels from the light_map_pic. Used when restoring a dynamicaly modified light_map.


light_map::map_point

Prototype

void map_point(float u, float v, vector &point)

Parameters

Parameter | Type | Description
u | float | point co-ordinate in the u axis
v | float | point co-ordinate in the v axis
point | vector & | point mapped in world space

Return Value

None

Remarks

This function maps a point from the light_map (u,v) into world co-ordinate.


light_map::save

Prototype

void save(light_map_pic *lmp)

Parameters

Parameter | Type | Description
lmp | light_map_pic * | light_map_pic with original light_map values

Return Value

None

Remarks

Saves the current light_map pixels into the original light_map_pic images. Used when saving the illumination into the light_map_pic (offline light computation).


light_map::set_base

Prototype

void set_base(face *f,light_map_pic *lmp,vector& pos=vector(0,0,0))

Parameters

Parameter | Type | Description
f | face * | face using the light_map
lmp | light_map_pic * | light_map_pic for this light_map
pos | vector& | position for the light_map in world co-ordinates

Return Value

None

Remarks

This function precompute internal data required when mapping points from the light_map space into world space and vice-versa.


class light_map_pic

Definition

class light_map_pic
{
public:
unsigned char *bmp;
int sizex,sizey;
int bytesx,bytesxy;
int bytespixel;

light_map_pic(int sx,int sy,int bp=3)
{
bytespixel=bp;
sizex=sx;
sizey=sy;
bytesx=sx*bytespixel;
if (bytesx&3) bytesx+=4-(bytesx&3);
bytesxy=bytesx*sizey;
bmp=new unsigned char [bytesxy];
};
virtual ~light_map_pic()
{
if(bmp) delete bmp;
};
};

Data Members

Member | Type | Description
bmp | char * | light_map_pic pixels
sizex | int | size in x (power of 2)
sizey | int | size in y (power of 2)
bytesx | int | number of bytes per line (sizex*bytespixel)
bytesxy | int | total bytes of the light_map_pic bmp (bytesx*sizey)
bytespixel | int | the light map bytes per pixel: 3 - RGB 4 - RGBA

Methods

constructor

Remarks

This class implements the light_map picture used when drawing. This picture can have several light_map pictures in it and many light_map classes will use a single light_map_pic.

See Also

light_map, flyEngine


light_map_pic constructors

light_map_pic constructor

Prototype

light_map_pic(int sx,int sy,int bp=3)

Parameters

Parameter | Type | Description
sx | int | size in x (power of 2)
sy | int | size in y (power of 2)
bp | int | the light map bytes per pixel: 3 - RGB 4 - RGBA

Remarks

Creates the light_map_pic and allocates the bitmap pixels.


class light_vertex

Definition

class light_vertex
{
vector pos[MAX_HWLIGHTS];
vector color[MAX_HWLIGHTS];
float radius[MAX_HWLIGHTS];
public:
int nlights;
light_vertex() { nlights=0; };
void add_light(vector& p,vector& c,float r);
void init_draw(bsp_object *obj);
void end_draw();
};

Data Members

Member | Type | Description
nlights | int | number of active lights
pos | vector[] | position of active lights
color | vector[] | color of active lights
radius | float[] | radius of active lights

Methods

add_light, init_draw, end_draw

Remarks

This class holds information on dynamic hardware lights. When a dynamic object receives a FLYOBJM_ILLUM message it adds the light parameters to this class with the add_light method. When rendering it calls the init_draw method before drawing the mesh to get the hardware lights in place. After finishing the render it calls end_draw to reset the hardware lights.

See Also

vector


light_vertex::add_light

Prototype

void add_light(vector& p,vector& c,float r)

Parameters

Parameter | Type | Description
p | vector& | light position
c | vector& | light color
r | float | light radius

Return Value

None

Remarks

This function adds a new light to the light_vertex array of lights. If the maximum number of hardware lights is exceeded, the light is not added.


light_vertex::end_draw

Prototype

void end_draw()

Parameters

None

Return Value

None

Remarks

Finishes hardware lights illumination by disabling all lights initialized with the init_lights function.


light_vertex::init_draw

Prototype

void init_draw(bsp_object *obj)

Parameters

Parameter | Type | Description
obj | bsp_object * | object that is to use the hardware lights

Return Value

None

Remarks

This function initializes and sets up the hardware lights stored in its light array. Each light is checked for shadows from the obj center position to the light position. After calling this function all geometry drawn will be lit with stored lights. To end lighting, end_draw must be called.


class local_system

Definition

class local_system
{
public:
vector X,Y,Z;
mat4x4 mat,mat_t;

void update_mat();
void rotate(vector& rot);
void rotate(float ang,vector& v);
void rotate(vector &v, vector &u, float maxang=360);
void align_z(vector& z);
};

Data Members

Member | Type | Description
X | vector | the X base axis
Y | vector | the Y base axis
Z | vector | the Z base axis
mat | mat4x4 | matrix rotating from local to global
mat_t | mat4x4 | matrix for rotating from global to local

Methods

update_mat, rotate, align_z

Remarks

This class implements a local system. A local system is defined by three perpendicular vectors (the base axis).

See Also

vector, mat4x4


loacal_system::align_z

local_system::align_z

Prototype

void align_z(vector& z)

Parameters

Parameter | Type | Description
z | vector& | the vector to align the Z axis with

Return Value

None

Remarks

This function aligns the Z axis from the local_system with the supplied vector.


local_system::rotate

Prototype

void rotate(vector& rot)
void rotate(float ang,vector& v);
void rotate(vector &from, vector &to, float maxang=360);

Parameters

Parameter | Type | Description
rot | vector& | rotation vector in degrees
ang | float | angle in degrees to rotate around vector v
v | vector& | vector to define rotation of angle degrees
from | vector& | vector to rotate from
to | vector& | vector to rotate to
maxang | float | maximum angle of rotation around cross product of from and to

Return Value

None

Remarks

This functions rotates the local_system axis and redefines the local_system matrices.
The first one, rotates rox.x around X axis, rot.y around Y axis and rot.z around Z axis.
The second one, rotates ang degrees around a vector v.
The third one, rotates from vector from to vector to, a maximum of maxang degrees. It rotates in the plane that contains the vectors from and to.


local_system::update_mat

Prototype

void update_mat()

Parameters

None

Return Value

None

Remarks

This function updates the mat and mat_t matrices to represent the rotation defined by the X, Y and Z local system axis. If the axes are changed, this function needs to be called in order to have the mat and mat_t variables updated.


class mat4x4

Definition

class mat4x4
{
public:
float m[4][4];

inline void null(void)
{
        memset(&m,0,sizeof(m));
    }

inline void load_identity(void)
{
memset(m,0,sizeof(m));
m[0][0]=m[1][1]=m[2][2]=m[3][3]=1.0;
}

void set_rotation( float ang, vector& dir );
mat4x4 operator*(mat4x4& m1)
};

Data Members

Member | Type | Description
m | float[][] | matrix elements

Methods

null, load_identity, set_rotation, operators

Remarks

This class implements a 4x4 matrix. The matrix can represent any linear transformation and is used for rotation, translation, scaling, etc...

See Also

vector

Example

mat4x4 m1,m2,m3;
m2.load_identity();
m3.load_identity();
m2.set_rotation(45,vector(0,0,1));
m3.set_rotation(30,vector(0,1,0));
m1=m2*m3;


mat4x4::load_identity

Prototype

inline void load_identity(void)

Parameters

None

Return Value

None

Remarks

Sets the matrix to the identity matrix. The diagonal elements are set to 1.0 and all others set to 0.0.


mat4x4::null

Prototype

inline void null(void)

Parameters

None

Return Value

None

Remarks

Sets all matrix elements to zero.


mat4x4 Operators

Prototype

mat4x4 operator*(mat4x4& m1)

Parameters

Parameter | Type | Description
m1 | mat4x4& | matrix to multiply current matrix

Remarks

This operator multiplies two matrices.


mat4x4::set_rotation

Prototype

void set_rotation( float ang, vector& dir )

Parameters

Parameter | Type | Description
ang | float | rotation angle in degrees
dir | vector& | rotation vector

Return Value

None

Remarks

This function multiplies the curremt matrix by a rotation matrix of ang degrees around vector dir.


class mesh

class mesh : public base_object

Definition

class mesh : public base_object
{
public:
int nv, nf;
vector *vert;
vector *vertnorm;
face **faces;
face *localfaces;
int *edges,nedges;
vector pivotpos;
boundbox bbox;
vector color;
float scrollu,scrollv;
int lastdraw;

mesh()
{
vert=0; vertnorm=0; faces=0; nv=0; nf=0; localfaces=0;
color.vec(1.0f,1.0f,1.0f,1.0f);
scrollu=scrollv=0.0f;
lastdraw=0;
};
virtual ~mesh()
{ reset(); };

void reset();
virtual void draw();
virtual void draw_cartoon(vector& campos,vector& light,light_vertex&
  lights,float edgewidth);
virtual void draw_shadow_volume(vector& lightdir);
int get_edge(int v1,int v2);
int load_3ds(char *name);
void compute_normals(int flag=15);
int ray_intersect(vector& ro,vector& rd,vector& ip,float&
  dist,float rad=0.0f);
int ray_intersect_test(vector& ro,vector& rd,float rad=0.0f);
void illum_faces(vector& ip,float d_max,vector& c,int shadows);
void implode(float mindist=0.1f);
void set_numverts(int nverts,int keep=0);
void set_numfaces(int nfaces,int local=0,int keep=0);
mesh *clone();
};

Data Members

Member | Type | Description
nv | int | number of vertices in the mesh
nf | int | number of faces in the mesh
vert | vector * | the vertices array
vertnorm | vector * | the vertex normals array
faces | face ** | the faces pointers array
localfaces | face * | the faces array
edges | int * | the edges array (4*sizeof(int)*nedges) each entry 4 integers: two vertices, two faces
nedges | int | the number of entries in edges list
pivotpos | vector | the mesh pivot position
bbox | boundbox | the mesh bounding box (aabb)
color | vector | the mesh color multiplier
scrollu | float | texture co-ordinates scroll factor in u direction
scrollv | float | texture co-ordinates scroll factor in v direction
lastdraw | int | last frame the mesh was draw

Methods

reset, draw, draw_cartoon, draw_shadow_volume, get_edge, load_3ds, compute_normals, ray_intersect, ray_intersect_test, illum_faces, implode, set_numverts, set_numfaces, clone

Remarks

This class implements a 3D mesh object. The mesh can have the faces defined in it (localfaces) or it can point to faces outside the mesh (from the bsp) by having the localfaces pointer set to NULL.

See Also

vector, plane, face, base_object


mesh::clone

Prototype

mesh *clone()

Parameters

None

Return Value

Returns the pointer to the cloned mesh.

Remarks

This function clones a mesh (duplicates it) and all its attributes (vertices, faces, etc...).


mesh::compute_normals

Prototype

void compute_normals(int flag=31)

Parameters

Parameter | Type | Description
flag | int | bit flag defining what should be computed: bit 1: implode vertices (weld) bit 2: face and edge normals bit 3: vert normals bit 4: bounding box bit 5: edges array

Return Value

None

Remarks

This function computes several mesh variables, for example, face normals, vertex normals, edge normals, face connectivity and bounding box.
Use the flag parameter to do a partial and faster computation.


mesh::draw

Prototype

virtual void draw()

Parameters

None

Return Value

None

Remarks

This function draws the mesh faces. The current color and texture co-ordinates scroll factor are used to modify the mesh faces colors and texture co-ordinates.


mesh::draw_cartoon

Prototype

virtual void draw_cartoon(vector& campos,vector& light,light_vertex& lights,float edgewidth)

Parameters

Parameter | Type | Description
campos | vector& | the camera position relative to the mesh
light | vector& | the ambient light
lights | light_vertex& | the dynamic lights to illuminate the cartoon
edgewidth | float | the cartoon edge (outline) width

Return Value

None

Remarks

This function draws the mesh as a cartoon.


mesh::draw_shadow_volume

Prototype

virtual void draw_shadow_volume(vector& lightdir)

Parameters

Parameter | Type | Description
lightdir | vector& | the light direction for the shadow volume

Return Value

None

Remarks

This function draws the the shadow volume used when rendering stencil shadows.


mesh::illum_faces

Prototype

void illum_faces(vector& p,float d_max,vector& c,int shadows)

Parameters

Parameter | Type | Description
p | vector& | light point
d_max | float | light radius
c | vector& | light color
shadows | int | shadow flags: 0 - no shadows 1 - shadow from specific object (flyengine::shadow_obj) 2 - gloabl shadows

Return Value

None

Remarks

This function illuminates the mesh faces light maps. It is used only on meshes with light maps like the static bsp leaf mesh.


mesh::implode

Prototype

void implode(float mindist=0.1f)

Parameters

Parameter | Type | Description
mindist | float | distance threshold for welding vertices

Return Value

None

Remarks

This function combines all vertices from the mesh that are closer than mindist into a single vertex.


mesh::load_3ds

Prototype

int load_3ds(char *name)

Parameters

Parameter | Type | Description
name | char * | filename for the .3ds file to load

Return Value

Returns TRUE is loading is OK, FALSE is could not load the file.

Remarks

This function loads a .3ds file into the mesh. Vertices, faces, textures and texture co-ordinates are loaded and it also computes all face normals, edge normals and vertex normals.


mesh::ray_intersect

Prototype

int ray_intersect(vector& ro,vector& rd,vector& ip,float& dist,float rad=0.0f)

Parameters

Parameter | Type | Description
ro | vector& | ray origin
rd | vector& | ray direction
ip | vector& | intersection point
dist | float& | intersection distance
rad | float& | collision radius

Return Value

Returns TRUE if an intersection is found, FALSE for no intersection.

Remarks

This function computes the ray intersection with the mesh.
If an intersection is found, ip will be set to the intersection point, dist will be set to the distance from the ray origin (ro) to the indersection point (ip).
If rd is normalized, the dist value will be in scene units, if not, if will be the distance divided by the ray direction (rd) length.
The rad parameter sets the collision radius. If >0, the collision will be tested for a sphere with radius rad.
All faces from the mesh are tested for intersection and the closest intersection is returned. The ray_intersect_test function is a faster version that returns the first intersection (good for when you just need to know if there is an intersection and do not care where).


mesh::ray_intersect_test

Prototype

int ray_intersect_test(vector& ro,vector& rd,float rad=0.0f)

Parameters

Parameter | Type | Description
ro | vector& | ray origin
rd | vector& | ray direction
rad | float | collision radius

Return Value

Returns TRUE if an intersection is found, FALSE for no intersection.

Remarks

This function tests for a collision with the mesh. It is faster then the ray_intersect function as it does not find the closest intersection, but returns at the first intersection encountered.


mesh::reset

Prototype

void reset()

Parameters

None

Return Value

None

Remarks

This function resets the mesh, freeing all faces, vertices and vertex normals.


mesh::set_numverts

Prototype

void set_numverts(int nverts,int keep=0)

Parameters

Parameter | Type | Description
nverts | int | new number of vertices
keep | int | keep old vertices array

Return Value

None

Remarks

This function is used to resize the vertex array of a mesh.

If keep is not zero, the newly allocated array will contain the data from previous vertex array.
If new number of vertices is bigger then original vertex count, all old vertices are maintained.
If new number of vertices is smaller then original vertex count, only the first nvert vertices will be kept.


mesh::set_numfaces

Prototype

void set_numfaces(int nfaces,int local=0,int keep=0);

Parameters

Parameter | Type | Description
nfaces | int | new number of faces
local | int | allocate local faces
keep | int | keep old faces

Return Value

None

Remarks

This function is used to resize the faces array of a mesh.

If local is not zero, local_faces will also be allocated.

If keep is not zero, the newly allocated array will contain the data from previous faces array.
If new number of faces is bigger then original face count, all old faces are maintained.
If new number of faces is smaller then original face count, only the first nfaces faces will be kept.


class mp_games

Definition

class mp_games
{
public:
int num;
char name[FLYMP_MAXGAMES][128];
int num_players[FLYMP_MAXGAMES];
GUID guid[FLYMP_MAXGAMES];

mp_games()
{ num=0; };
};

Data Members

Member | Type | Description
num | int | number of games
name | char[][] | game names array
num_players | int[] | number of players array
guid | GUID[] | games GUID array

Methods

None

Remarks

This class is used to enumerate games on a specific server.
Use the enum_games function to get a pointer to this class. The class will be filled with information on all games available to join. Pass the guid field of the selected game to the join_game function to enter the game.

See Also

directX, mp_msg


class mp_msg

Definition

class mp_msg
{
public:
DWORD type;
DWORD from;
char data[500];
};

Data Members

Member | Type | Description
type | DWORD | message type
from | DWORD | directplay player id of the message sender
data | char[] | the message data (up to 500 bytes)

Methods

None

Remarks

This class implements a multiplayer message. All messages must begin with type and from fields. The data field can be of any size up to 500 bytes.

See Also

directX, mp_games


class param_desc

Definition

class param_desc
{
public:
char name[64];
int type;
void *data;

char *get_string();
void set_string(char *str);
};

Data Members

Member | Type | Description
name | char [] | the parameter name
type | int | the parameter type
data | void * | pointer to the parameter data

Methods

get_string, set_string

Remarks

This class holds information on Fly3D plug-in object parameters. Each class defined in a Fly3D plug-in (derived from bsp_object) can have any number of parameters. Each parameter must have an associated param_desc class describing its data.

The types of parameters available are:

>255 - parameter is a pointer to a class in the stock obejcts list that has this type id
<255 - parameter is a pointer to a class in the active objects list that has this type id

Type | Description | Data type | Data size (sizeof)
‘a’ | angle | float | 4
‘i’ | integer | int | 4
‘f ‘ | floating point | float | 4
‘v’ | float vector (x,y,z) | vector | 12
‘c’ | float color (r,g,b) | vector | 12
‘b’ | Bezier curve | bezier_curve * | 4
'h' | Bezier patch | bezier_patch * | 4
‘3’ | 3ds mesh model | mesh * | 4
‘m’ | fao animate mesh | anim_mesh * | 4
‘w’ | wav sound object | sound * | 4
‘p’ | picture file | int | 4
‘o’ | stock object | bsp_object * | 4
‘d’ | active object | bsp_object * | 4

See Also

class_desc, flydll, flydllgroup


param_desc::get_string

Prototype

char *get_string()

Parameters

None

Return Value

Returns the parameter formatted as a string.

Remarks

This function is used to format a parameter as a string. It will get numbers, vectors, object names or file names depending on the parameter type.


param_desc::set_string

Prototype

void set_string(char *str)

Parameters

Parameter | Type | Description
str | char * | formatted string to set parameter from

Return Value

None

Remarks

This function sets the parameter from a formatted string. The string can be a number, vector, color, object name or file name depending on the perameter type.


class particle

Definition

class particle
{
public:
vector pos, vel, force;
float mass, bump, friction, radius;
int life;
int col_flag;

int compute_collision(vector& p,vector& v);
int step(int dt);
};

Data Members

Member | Type | Description
pos | vector | position
vel | vector | velocity
force | vector | force
mass | float | mass
bump | float | bump factor (0 to 1): 0 - no bump 1 - maximum bump
friction | float | friction factor (0 to 1): 0 - maximum friction 1 - no friction
radius | float | radius
life | int | life in ms
col_flag | int | bit flag for collision: bit 1: collision on/off bit 2: collide and die

Methods

compute_collision, step

Remarks

This class implements a particle.

See Also

vector


particle::compute_collision

Prototype

int compute_collision(vector& p,vector& v)

Parameters

Parameter | Type | Description
p | vector& | target position
v | vector& | target velocity

Return Value

Returns TRUE if a collision was found, FALSE for no collision.

Remarks

This function is used to compute collision for a moving particle. The p and v parameters are the new computed position and velocity parameters. If a collision is found between p and the current position, then both p and v will be modified accordingly.


particle::step

Prototype

int step(int dt)

Parameters

Parameter | Type | Description
dt | int | elapsed time in ms

Return Value

Returns TRUE is particle moved, FALSE if particle did not move.

Remarks

This function updates the particle for an specified elapsed time. The particle will be moved based according to its current velocity and the velocity will be updated using the current force and mass. If the collision flag is turned on, collision will be tested and the position and velocity will be changed based on collsion point, normal, bump, and friction factors.


class picture

Definition

class picture
{
public:
char name[256];
int sx,sy,bytespixel,size;
unsigned char **buf;

picture();

int LoadTGA(char *file);
int SaveTGA(char *file);
int LoadPIC(char *file);
int LoadJPG(char *file);
int CreatePicture32(int xd,int yd);
int CreatePicture24(int xd,int yd);
void FreePicture(void);
void ErasePicture(char c);

virtual ~picture();
};

Data Members

Member | Type | Description
name | char [] | picture filename
sx | int | x size in pixels
sy | int | y size in pixels
bytespixel | int | number of bytes per pixel (24 or 32)
size | int | size in bytes for the image (sx*sy*bytespixel)
buf | unsigned char ** | image pixels

Methods

LoadTGA, SaveTGA, LoadPIC, LoadJPG, CreatePicture32, CreatePicture24, FreePicture

Remarks

This class implements a picture with 24 or 32 bits/pixel. The picture pixels are allocated in a single array of bytes (buf[0]) and the other variables are just shortcuts to the picture lines (buf[1] to buf[sy-1]).

See Also

flyEngine

Example

picture p;
p.LoadJPG("mypic.jpg");
p.SaveTGA("mypic.tga");


picture::CreatePicture32

Prototype

int CreatePicture32(int xd,int yd)

Parameters

Parameter | Type | Description
xd | int | x size in pixels
yd | int | y size in pixels

Return Value

Returns TRUE if creation is OK, FALSE on any error.

Remarks

This function allocates the memory required for the a picture with the specified dimensions. The buffer allocated is xc*yd*4 bytes.


picture::CreatePicture24

Prototype

int CreatePicture24(int xd,int yd)

Parameters

Parameter | Type | Description
xd | int | x size in pixels
yd | int | y size in pixels

Return Value

Returns TRUE if creation is OK, FALSE on any error.

Remarks

This function allocates the memory required for the a picture with the specified dimensions. The buffer allocated is xc*yd*3 bytes.


picture::FreePicture

Prototype

void FreePicture(void)

Parameters

None

Return Value

None

Remarks

This function frees all data allocated by the picture.


picture::LoadJPG

Prototype

int LoadJPG(char *file)

Parameters

Parameter | Type | Description
file | char * | filename for the .jpg image to load

Return Value

Returns TRUE if loading is OK, FALSE an any error.

Remarks

This function loads a .jpg image. The image can be a standalone file or it can be included in a .fpk package file.


picture::LoadPic

Prototype

int LoadPIC(char *file)

Parameters

Parameter | Type | Description
file | char * | filename for the image to load

Return Value

Returns TRUE if loading is OK, FALSE an any error.

Remarks

This function is used to load an image. The extension is looked up and depending on the type of image (TGA or JPG) the appropriate loading function is called.


picture::LoadTGA

Prototype

int LoadTGA(char *file)

Parameters

Parameter | Type | Description
file | char * | filename for the .tga image to load

Return Value

Returns TRUE if loading is OK, FALSE an any error.

Remarks

This function loads a .tga image. The image can be a standalone file or it can be included in a .fpk package file. Only 24 or 32 bits/pixel images are supported and they can be uncompressed or RLE compressed.


picture::SaveTGA

Prototype

int SaveTGA(char *file)

Parameters

Parameter | Type | Description
file | char * | filename for .tga file to save

Return Value

Returns TRUE is saving is OK, FALSE on any error.

Remarks

This function saves a picture into a uncompressed .tga file. 24 or 32 bits/pixels images are supported.


plane

class plane

Definition

class plane
{
public:
vector normal;
float d0;

inline float distance(vector &v)
{ return vec_dot(normal,v)+d0; }
};

Data Members

Member | Type | Description
normal | vector | normalized plane normal
d0 | float | smallest distance from plane to origin.

Methods

distance

Remarks

This class implements a plane is 3D space.
Classes like the bsp_node and face derive from a plane.

See Also

vector, bsp_node, face


plane::distance

Prototype

inline float distance(vector &v)
{ return vec_dot(normal,v)+d0; };

Parameters

Parameter | Type | Description
v | vector& | point from where distance is to be calculated

Return Value

Returns the smallest distance from the specified point to the plane.

Remarks

This method calculates the perpendicular distance from the specified point to the plane.
If distance is zero, the point is in the plane surface.
A positive distance means the point is in the front side of the plane (same side as the plane normal).
A negative distance means the point is in the back side of the plane.


class player_data

Definition

class player_data
{
public:
DWORD type,dpid;
char name[32];
void *data;

player_data()
{ memset(this,0,sizeof(player_data));};
};

Data Members

Member | Type | Description
type | DWORD | player type (client or server)
dpid | DWORD | direct play player id
name | char[] | player name
data | void * | player generic data

Methods

None

Remarks

This class hold information on players in a multiplayer game. Usualy the data part of the class points to the player bsp_object.

See Also

directX


class render

Definition

class render
{
public:
int type;

virtual ~render()
{ ; };

virtual int CreateView(HWND wnd)=0;
virtual void DeleteView()=0;
virtual void ResizeView(int sx,int sy)=0;
virtual void InitView()=0;
virtual void DrawView()=0;
virtual void SetFullScreen()=0;
};

Data Members

Member | Type | Description
type | int | render type: 0 - None 1 - OpenGL

Methods

CreateView, DeleteView, ResizeView, InitView, DrawView, SetFullScreen

Remarks

This is the base class for the render. The OpenGL implementation of the render is made by sub-classing this class and implementing its virtual function in the selected graphics API.
A global variable named render is the main interface with this class and must be initialized/freed with the init_render and close_render global functions.

See Also

Global Variables, Global Functions, renderGL


render::CreateView

Prototype

virtual int CreateView(HWND wnd)=0

Parameters

Parameter | Type | Description
wnd | HWND | view window handle

Return Value

Returns TRUE is view is created, FALSE for any error.

Remarks

This virtual function should create the render view and attach it to the supplied window.


render::DeleteView

Prototype

virtual void DeleteView()=0

Parameters

None

Return Value

None

Remarks

This virtual function should delete the render view and free any associated resources.


render::DrawView

Prototype

virtual void DrawView()=0

Parameters

None

Return Value

None

Remarks

This virtual function is called to render the scene. Sub-classes should does the following order of operations:
1) Computes the elapsed time from last frame.
2) Call InitView to initialize global render setting for the frame
3) Clear the Z-buffer, color buffer is flyengine->clearbk is TRUE and stencil buffer if flyengine->stencil is TRUE
4) Call flyengine->step passing elapsed time (update all scene and plug-in objects)
5) Swap buffers to display rendered image


render::InitView

Prototype

virtual void InitView()=0

Parameters

None

Return Value

None

Remarks

This virtual function is used to initialize the global default state for the render. It is called before starting each frame and is where all render general settings must occur.


render::ResizeView

Prototype

virtual void ResizeView(int sx,int sy)=0

Parameters

Parameter | Type | Description
sx | int | new size in x
sy | int | new size in y

Return Value

None

Remarks

This virtual function is used when the render view changes its size. It should resize the render view to the new dimensions defiend by the sx and sy parameters.


render::SetFullScreen

Prototype

virtual void SetFullScreen()=0

Parameters

None

Return Value

None

Remarks

This virtual function handles window/fullscreen changes. When called it must check the global variable fullscreen and:
If it is 0, switch to window mode
If it is 1, switch to fullscreen mode using the selected video mode defined in the selvideomode global variable


class class_name

class renderGL : public render

Definition

class renderGL : public render
{
public:
HGLRC m_hRC;
HDC hdc;
HWND hWnd;

renderGL()
{ type=FLY_RENDER_OPENGL; hdc=0; hWnd=0; m_hRC=0; active=1; };
virtual ~renderGL()
{ DeleteView(); };

int CreateView(HWND wnd);
void DeleteView();
void ResizeView(int sx,int sy);
void InitView();
void DrawView();
void SetFullScreen();
};

Data Members

Member | Type | Description
m_hRC | HGLRC | OpenGL handle
hdc | HDC | device context handle
hWnd | HWND | window handle

Methods

CreateView, DeleteView, ResizeView, InitView, DrawView, SetFullScreen

Remarks

This is the OpenGL implementation of the base render class. All OpenGL initializing and render view changes are implemented in its virtual functions.
A global variable named render is the main interface with this class and must be initialized/freed with the init_render and close_render global functions.

See Also

Global Variables, Global Functions, render


renderGL::CreateView

Prototype

int CreateView(HWND wnd)

Parameters

Parameter | Type | Description
wnd | HWND | view window handle

Return Value

Returns TRUE is view is created, FALSE for any error.

Remarks

This is the OpenGL implementation for the render base class virtual function.

This function creates the render view and attaches it to the supplied window.


class_name::method_name

renderGL::DeleteView

Prototype

void DeleteView()

Parameters

None

Return Value

None

Remarks

This is the OpenGL implementation for the render base class virtual function.

This function deletes the render view and free any associated resources.


renderGL::DrawView

Prototype

void DrawView()

Parameters

None

Return Value

None

Remarks

This is the OpenGL implementation for the render base class virtual function.

It is called to render the scene and does the following order of operations:
1) Calls InitView to initialize global render setting for the frame
2) Clears the zbuffer, color buffer is flyengine->clearbk is TRUE and stencil buffer if flyengine->stencil is TRUE
3) Draws the scene and all objects inside view frustum
4) Initialize text mode and draw all 2D stuff
5) Swaps buffers to display rendered image


renderGL::InitView

Prototype

void InitView()

Parameters

None

Return Value

None

Remarks

This is the OpenGL implementation for the render base class virtual function.

This virtual function is used to initialize the global default state for the render. It is called before starting each frame and is where all render general settings must occur.


renderGL::ResizeView

Prototype

void ResizeView(int sx,int sy)

Parameters

Parameter | Type | Description
sx | int | new size in x
sy | int | new size in y

Return Value

None

Remarks

This is the OpenGL implementation for the render base class virtual function.

This function is used when the render view changes its size. It resizes the render view to the new dimensions defined by the sx and sy parameters.


renderGL::SetFullScreen

Prototype

void SetFullScreen()

Parameters

None

Return Value

None

Remarks

This is the OpenGL implementation for the render base class virtual function.

It handles window/fullscreen changes. It checks the global variable fullscreen and:
If it is 0, it switches to window mode.
If it is 1, it switches to fullscreen mode using the selected video mode defined in the selvideomode global variable.


class sound

class sound : public base_object

Definition

class sound : public base_object
{
public:
int total_time;
LPDIRECTSOUNDBUFFER buf;
LPDIRECTSOUND3DBUFFER buf3d;

sound()
{ buf=0; buf3d=0; total_time=0; };

virtual ~sound()
{ reset(); };

void reset()
{
if (buf3d) buf3d->Release(); buf3d=0;
if (buf) buf->Release(); buf=0;
total_time=0;
}

int load_wav(char *filename);
sound *clone();
};

Data Members

Member | Type | Description
total_time | int | the sound length in ms
buf | LPDIRECTSOUNDBUFFER | the DirectX sound buffer
buf3d | LPDIRECTSOUND3DBUFFER | the DirectX sound buffer 3D

Methods

reset, load_wav, clone

Remarks

This class implements raw sound data. The sound can be loaded from a .wav file.
For playing multiple instances of the same sound, you must clone it and play the clones.

See Also

base_object, directX


sound::clone

Prototype

sound *clone()

Parameters

None

Return Value

Returns the cloned sound class pointer.

Remarks

This function clones the sound buffer for simultaneous sound playback.


sound::load_wav

Prototype

int load_wav(char *filename)

Parameters

Parameter | Type | Description
filename | char * | the filename for the .wav sound file to load

Return Value

Returns TRUE if loading is OK, FALSE if the file could not be loaded.

Remarks

This function loads a .wav file (standalone or from a .fpk package).


sound::reset

Prototype

void reset()

Parameters

None

Return Value

None

Remarks

Resets the class freeing the DirectX sound buffers.


class static_mesh

class static_mesh : public bsp_object

Definition

class static_mesh : public bsp_object
{
public:
mesh *objmesh;

static_mesh()
{ type=TYPE_STATIC_MESH; objmesh=new mesh; };

mesh *ray_intersect(vector& ro,vector& rd,vector& ip,float&
dist,int &facenum,float rad=0.0f);
int ray_intersect_test(vector& ro,vector& rd,float rad);
int message(vector& p,float rad,int msg,int param,void *data);

virtual ~static_mesh()
{ if (objmesh) delete objmesh; };
};

Data Members

Member | Type | Description
mesh | objmesh * | mesh with some bsp faces

Methods

ray_intersect, ray_intersect_test, message

Remarks

This class implements the bsp faces in a bsp leaf node. All leaf nodes have a static_object as their first bsp_node element in the elem linked list. It is just like a Fly3D plug-in object and in the only plug-in object already included in the engine dll.

See Also

mesh, bsp_object, bsp_node


static_mesh::message

Prototype

int message(vector& p,float rad,int msg,int param,void *data)

Parameters

Parameter | Type | Description
p | vector& | position
rad | float | radius
msg | int | type
param | int | parameter
data | void * | general pointer parameter

Return Value

Returns 0 continue the message chain.

Remarks

This function processes the messages sent to the bsp leaf faces. It handles static and dynamic lighting messages.


static_mesh::ray_intersect

Prototype

mesh *ray_intersect(vector& ro,vector& rd,vector& ip,float& dist,int &facenum,float rad=0.0f);

Parameters

Parameter | Type | Description
ro | vector& | ray origin
rd | vector& | ray direction
ip | vector& | intersection point
dist | float& | intersection distance
facenum | int& | intersected face index into returned mesh
rad | float | collision radius

Return Value

Returns the mesh object if a collision is detected, NULL on no collision.

Remarks

This function implements the ray intersection virtual bsp_obect function for the bsp faces included in a leaf node.
It passes the ray_intersect call to the same function from its objmesh member variable.


static_mesh::ray_intersect_test

Prototype

int ray_intersect_test(vector& ro,vector& rd,float rad)

Parameters

Parameter | Type | Description
ro | vector& | ray origin
rd | vector& | ray direction
rad | float | collision radius

Return Value

Returns TRUE if an intersection is found, FALSE for no intersection.

Remarks

This function implements the ray intersection test virtual bsp_obect function for the bsp faces included in a leaf node.
It passes the ray_intersect_test call to the same function from its objmesh member variable.


class stripfan_mesh

Definition

class stripfan_mesh
{
public:
int nstripfan;
int *stripfandata;
int nvert;
vertex *vertdata;

stripfan_mesh()
{ nstripfan=0; stripfandata=0; vertdata=0; nvert=0; }

void draw();
mesh *build_mesh();
vertex *add_stripfan(int nvert,int texpic,int lmpic);

void reset()
{
if (stripfandata) delete stripfandata;
if (vertdata) delete vertdata;
nstripfan=0; stripfandata=0; vertdata=0; nvert=0;
}

virtual ~stripfan_mesh()
{ reset(); }
};

Data Members

Member | Type | Description
nstripfan | int | number of strips and fans
stripfandata | int * | data for the strips and fans. 3 integers for each strip/fan.
nvert | int | number of vertices in vertdata array
vertdata | vertex * | vertices array

Methods

draw, build_mesh, add_stripfan, reset

Remarks

This class implements a mesh made of strips and fans. Each strip/fan is made of an array of vertex classes.
The stripfandata is an array of integers with nstripfan*3 elements. Each 3 elements defines a strip/fan as follwos:
1) The first element is the number of vertices for the strip/fan. If positive, it means a strip with n vertices. If negative, a fan with -n vertices.
2) The second element is the texture applied to strip/fan. If -1, no texture.
3) The third element is the light map applied to strip/fan. If -1, no light map.

See Also

mesh


stripfan_mesh::add_stripfan

Prototype

vertex *add_stripfan(int nvert,int texpic,int lmpic)

Parameters

Parameter | Type | Description
nvert | int | number of vertices to add
texpic | int | texture picture for this strip/fan
lmpic | int | light map for this strip/fan

Return Value

Return the pointer to the actual vertices added for the strip/fan.

Remarks

This function adds a new strip or fan to the mesh. If nvert is positive, it means a strip, if negative, means a fan.
Each strip/fan can have its own texture and light map. If strip has no texture or no light map, use -1 for the texture or light map parameter.
You must fill the strip vertices (position, color, texture co-ordinate and light map co-ordinate) using the returned pointer. It points to an array of vertices of size abs(nvert).


stripfan_mesh::build_mesh

Prototype

mesh *build_mesh()

Parameters

None

Return Value

Returns a mesh object representing the strip/fan object.

Remarks

This function converts the strip/fan mesh into a standard mesh.


stripfan_mesh::draw

Prototype

void draw()

Parameters

None

Return Value

None

Remarks

Draws the strip/fan mesh.


stripfan_mesh::reset

Prototype

void reset()

Parameters

None

Return Value

None

Remarks

This function clears the strip/fan mesh freeing all allocated data.


class textcache

Definition

class textcache
{
public:
int curpic[MAX_TEXTURE_UNITS];
int npic,curtextunit;

virtual void use(int pic=-1,int textunit=0)=0;
virtual void use_triangles(int pic=-1,int textunit=0)=0;
virtual void init(int np,picture **pic)=0;

virtual int add_picture(int sx,int sy,int bytespixel,unsigned char
  *lm)=0;
virtual void update_picture(int picnum,int sx,int sy,int bytespixel,unsigned
  char *buf)=0;
virtual void update_sub_picture(int picnum,int x,int y,int sx,int
  sy,int bytespixel,unsigned char *buf)=0;

textcache()
{
memset(curpic,-1,sizeof(int)*MAX_TEXTURE_UNITS);
npic=0;
curtextunit=0;
};

virtual ~textcache() { };
};

Data Members

Member | Type | Description
curpic | int [] | the current selected texture in each texture unit
npic | int | the total number of textures
curtextunit | int | the current selected texture unit

Methods

use, use_triangles, init, add_picture, update_picture, update_sub_picture

Remarks

This class in the base class for the texture cache (texture manager). Sub-classes from this class should implement their functionality by implementing the virtual functions using the the selected graphics API.
Use the flyEngine init_texture_cache and free_texture_cache to initialize and free the global variable tc that is the main interface to this class.

See Also

Global Variables, textcacheGL, flyEngine


textcache::add_picture

Prototype

virtual int add_picture(int sx,int sy,int bytespixel,unsigned char *lm)=0

Parameters

Parameter | Type | Description
sx | int | size in x (power of 2)
sy | int | size in y (power of 2)
bytespixel | int | bytes per pixel (3 or 4)
lm | unsigned char * | picture pixels (sx*sy*bytespixel)

Return Value

Returns the newly created picture index.

Remarks

This virtual function is used to add a new picture to the texture manager.


textcache::init

Prototype

virtual void init(int np,picture **pic,void *data)=0

Parameters

Parameter | Type | Description
np | int | number of pictures in pic array
pic | picture ** | picture array

Return Value

None

Remarks

This virtual function initializes the texture manager with a picture array. All pictures in the array will be loaded to the 3D hardware. For adding new pictures, use the add_picture function, for updating any picture pixels, use the update_picture and update_sub_picture member functions.


textcache::update_picture

Prototype

virtual void update_picture(int picnum,int sx,int sy,int bytespixel,unsigned char *buf)=0

Parameters

Parameter | Type | Description
picnum | int | picture index
sx | int | size in x (power of 2)
sy | int | size in y (power of 2)
bytespixel | int | bytes per pixel (3 or 4)
buf | unsigned char * | picture pixels (sx*sy*bytespixel)

Return Value

None

Remarks

This virtual function is used to update the picture in the picture manager with a new pixel array.


textcache::update_sub_picture

Prototype

virtual void update_sub_picture(int picnum,int x,int y,int sx,int sy,int bytespixel,unsigned char *buf)=0

Parameters

Parameter | Type | Description
picnum | int | picture index
x | int | x offset
y | int | y offset
sx | int | size in x (no need to be power of 2)
sy | int | size in y (no need to be power of 2)
bytespixel | int | bytes per pixel (3 or 4)
buf | unsigned char * | picture pixels ((sx*bytespixel aligned to 4 bytes)*sy)

Return Value

None

Remarks

This virtual function is used to update just a part of a picture in the texture manager. Only the sub-picture pixels are passed. If x and y are 0 and sx and sy the size of the image, it will work just like the update_picture function.


textcache::use

Prototype

virtual void use(int pic=-1,int textunit=0)=0

Parameters

Parameter | Type | Description
pic | int | picture index to select
textunit | int | texture unit to select

Return Value

None

Remarks

This virtual function selects a picture to be used in the specified texture unit. The texture unit remains selected and active after the call. Calling this function with pic=-1 will disable texturing in the specified texture unit. The number of texture units available is at the ntextureunits global variable.


textcache::use_triangles

Prototype

virtual void use_triangles(int pic=-1,int textunit=0)=0

Parameters

Parameter | Type | Description
pic | int | picture index to selected
textunit | int | texture unit to select

Return Value

None

Remarks

This virtual function selects a picture to be used in the specified texture unit. The texture unit remains selected and active after the call. Calling this function with pic=-1 will disable texturing in the specified texture unit. The number of texture units available is in the ntextureunits global variable. This is a variation of the use function that can be called between glBegin/glEnd pairs.


class textcacheGL

class textcacheGL : public textcache

Definition

class textcacheGL : public textcache
{
public:
textcacheGL();
~textcacheGL();

unsigned *tex;

void init(int np,picture **pic);

int add_picture(int sx,int sy,int bytespixel,unsigned char *buf);
void update_picture(int picnum,int sx,int sy,int bytespixel,unsigned
  char *buf);
void update_sub_picture(int picnum,int x,int y,int sx,int sy,int
  bytespixel,unsigned char *buf);

inline void use(int pic=-1,int textunit=0);
inline void use_triangles(int pic=-1,int textunit=0);
};

Data Members

Member | Type | Description
tex | unsigned * | the OpenGL texture handles

Methods

add_picture, update_picture, update_sub_picture, use, use_triangles, init

Remarks

This class is the OpenGL implementation sub-classed from the textcache base class.
Use the flyEngine init_texture_cache and free_texture_cache to initialize and free the global variable tc that is the main interface to this class.

See Also

Global Variables, textcache, flyEngine


textcacheGL::add_picture

Prototype

int add_picture(int sx,int sy,int bytespixel,unsigned char *buf)

Parameters

Parameter | Type | Description
sx | int | size in x (power of 2)
sy | int | size in y (power of 2)
bytespixel | int | bytes per pixel (3 or 4)
buf | unsigned char * | picture pixels (sx*sy*bytespixel)

Return Value

Returns the newly created picture index.

Remarks

This is the OpenGL implementation for the textcache base class virtual function.

This function is used to add a new picture to the texture manager.


textcacheGL::init

Prototype

void init(int np,picture **pic,void *data)

Parameters

Parameter | Type | Description
np | int | number of pictures in pic array
pic | picture ** | picture array

Return Value

None

Remarks

This is the OpenGL implementation for the textcache base class virtual function.

This function initializes the texture manager with a picture array. All pictures in the array will be loaded into the 3D hardware. For adding new pictures, use the add_picture function, for updating any picture pixels, use the update_picture and update_sub_picture member functions.


textcacheGL::update_picture

Prototype

void update_picture(int picnum,int sx,int sy,int bytespixel,unsigned char *buf)

Parameters

Parameter | Type | Description
picnum | int | picture index
sx | int | size in x (power of 2)
sy | int | size in y (power of 2)
bytespixel | int | bytes per pixel (3 or 4)
buf | unsigned char * | picture pixels (sx*sy*bytespixel)

Return Value

None

Remarks

This is the OpenGL implementation for the textcache base class virtual function.

This function is used to update the picture in the picture manager with a new pixel array.


textcacheGL::update_sub_picture

Prototype

void update_sub_picture(int picnum,int x,int y,int sx,int sy,int bytespixel,unsigned char *buf)

Parameters

Parameter | Type | Description
picnum | int | picture index
x | int | x offset
y | int | y offset
sx | int | size in x (no need to be power of 2)
sy | int | size in y (no need to be power of 2)
bytespixel | int | bytes per pixel (3 or 4)
buf | unsigned char * | picture pixels ((sx*bytespixel aligned to 4 bytes)*sy)

Return Value

None

Remarks

This is the OpenGL implementation for the textcache base class virtual function.

This function is used to update just a part of a picture in the texture manager. Only the sub-picture pixels are passed. If x and y are 0 and sx and sy the size of the image, it will work just like the update_picture function.


textcacheGL::use

Prototype

inline void use(int pic=-1,int textunit=0)

Parameters

Parameter | Type | Description
pic | int | picture index to select
textunit | int | texture unit to select

Return Value

None

Remarks

This is the OpenGL implementation for the textcache base class virtual function.

This function selects a picture to be used in the specified texture unit. The texture unit remains selected and active after the call. Calling this function with pic=-1 will disable texturing in the specified texture unit. The number of texture units available is at the ntextureunits global variable.


textcacheGL::use_triangles

Prototype

inline void use_triangles(int pic=-1,int textunit=0)

Parameters

Parameter | Type | Description
pic | int | picture index to select
textunit | int | texture unit to select

Return Value

None

Remarks

This is the OpenGL implementation for the textcache base class virtual function.

This function selects a picture to be used in the specified texture unit. The texture unit remains selected and active after the call. Calling this function with pic=-1 will disable texturing in the specified texture unit. The number of texture units available is at the ntextureunits global variable. This is a variation of the use function that can be called between glBegin/glEnd pairs.


vector

class vector

Definition

class vector
{
public:
float x,y,z,w;

inline vector()
{ ; };

inline vector(float x0,float y0,float z0)
{ x=x0; y=y0; z=z0; };

inline vector(float x0,float y0,float z0,float w0)
{ x=x0; y=y0; z=z0; w=w0; };

inline vector(vector &v)
{ *this=v; };

inline void null(void)
{ x=y=z=0; };

inline float length(void)
{ return (float)sqrt(x*x+y*y+z*z); };

inline void vec(float x0,float y0,float z0)
{ x=x0; y=y0; z=z0; };

inline void negate(void)
{ x=-x; y=-y; z=-z; };

inline void cross(vector& v1,vector& v2)
{
x=v1.y*v2.z-v1.z*v2.y;
y=v1.z*v2.x-v1.x*v2.z;
z=v1.x*v2.y-v1.y*v2.x;
}

inline void normalize(void)
{
float len=(float)sqrt(x*x+y*y+z*z);
if (len==0.0f) return; x/=len; y/=len; z/=len;
}

inline float& operator[](int i)
{ return (&x)[i]; };
};

Data Members

Member | Type | Description
x | float | vector co-ordinate in the X axis
y | float | vector co-ordinate in the Y axis
z | float | vector co-ordinate in the Z axis

Methods

constructors, null, length, vec, negate, cross, normalize, operator[]

Remarks

This class implements a 3D vector with four co-ordinates x, y, z and w. It is used for specifying points in 3D space, directions, velocity, force and also color (x is red, y is green, z is blue and w is alpha). The w co-ordinate is usually set to 1.0 when using the vector to represent 3D points and from 0.0 to 1.0 when using it as the color alpha value.

See Also

mat4x4


vector constructors

Prototype

inline vector()
{ ; };

inline vector(float x0,float y0,float z0)
{ x=x0; y=y0; z=z0; };

inline vector(float x0,float y0,float z0,float w0)
{ x=x0; y=y0; z=z0; w=w0; };

inline vector(vector &v)
{ *this=v; };

Parameters

Parameter | Type | Description
x0 | float | co-ordinate in X axis
y0 | float | co-ordinate in Y axis
z0 | float | co-ordinate in Z axis
w0 | float | co-ordinate in W axis
v | vector& | vector to clone

Remarks

Creates a new initialized or uninitialized vector.


vector::operator[]

Prototype

inline float& operator[](int i)

Parameters

Parameter | Type | Description
i | int | index into the vector (0 for x, 1 for y and 2 for z,3 for w)

Remarks

Returns the indexed vector co-ordinate. Index must be between 0 and 3.


vector::cross

Prototype

inline void cross(vector& v1,vector& v2)

Parameters

Parameter | Type | Description
v1 | vector& | First vector for cross product.
v2 | vector& | Second vector for cross product.

Return Value

None

Remarks

Sets the vector to the cross product of two specified vectors.
x = v1.y*v2.z - v1.z*v2.y;
y = v1.z*v2.x - v1.x*v2.z;
z = v1.x*v2.y - v1.y*v2.x;


vector::vec

Prototype

inline void vec(float x0,float y0,float z0)
inline void vec(float x0,float y0,float z0,float w0)

Parameters

Parameter | Type | Description
x0 | float | co-ordinate in X axis
y0 | float | co-ordinate in Y axis
z0 | float | co-ordinate in Z axis
w0 | float | co-ordinate in W axis

Return Value

None

Remarks

Sets vector co-ordinates.


vector::negate

Prototype

inline void negate()

Parameters

None

Return Value

None

Remarks

Inverts all vector co-ordinates.
x=-x, y=-x, z=-z


vector::null

Prototype

inline void null()

Parameters

None

Return Value

None

Remarks

Zero all vector co-ordinates.


vector::length

Prototype

inline float length()

Parameters

None

Return Value

Returns the length of the vector.

Remarks

This function return the length of the vector.
srqt(x*x + y*y + z*z)


vector::normalize

Prototype

inline void normalize()

Parameters

None

Return Value

None

Remarks

Normalizes the vector dividing each co-ordinate by the vector length.


flyEngine::get_obj_param

Prototype

int get_obj_param(char *objname,char *param,char *value)

Parameters

Parameter | Type | Description
objname | char * | object name
param | char * | parameter name
value | char * | string to receive the parameter value

Return Value

Returns 0 if parameter was found and value is set, 1 if object not found and 2 if parameter not found.

Remarks

This function is used to get a string representation of an object's parameter.


flyEngine::get_picture

Prototype

int get_picture(char *file)

Parameters

Parameter | Type | Description
file | char * | picture name

Return Value

Returns the picture index into picture array or -1 if picture could not be found.

Remarks

This function is used to get pictures from the stock. It returns the picture index for a given string based picture name. If picture is not in the pictures array, it attempts to load the picture from disk.


flyEngine::get_random_point

Prototype

bsp_node *get_random_point(vector& v,float mindist)

Parameters

Parameter | Type | Description
v | vector& | point
mnidist | float | minimum distance

Return Value

Returns the bsp leaf the random point v is in.

Remarks

This function is used to compute a random position inside the level that is at least mindist away from any wall. The random position will be stored in the v parameter.


flyEngine::get_sound_object

Prototype

sound *get_sound_object(char *name)

Parameters

Parameter | Type | Description
name | char * | sound name

Return Value

Returns a pointer to the given sound or NULL if sound not found.

Remarks

This function is used to get sounds from the stock. It returns the sound pointer for a given string based sound name. If sound is not in the sounds linked list, it attempts to load the sound from disk.


flyEngine::get_stock_object

Prototype

bsp_object *get_stock_object(char *name)

Parameters

Parameter | Type | Description
name | char * | object name

Return Value

Returns a pointer to the given object or NULL if object not found.

Remarks

This function is used to get objects from the stock objects linked list. It returns the object pointer for a given string based name.


mesh::get_edge

Prototype

int get_edge(int v1,int v2)

Parameters

Parameter | Type | Description
v1 | int | first vertex defining the edge
v2 | int | second vertex defining the edge

Return Value

Retuns the index into the edges array for the specified edge (v1,v2) or -1 if edge is not in edges list.

Remarks

This function is used for finding the index into the edges array for a specified edge difined by a pair of vertices (v1,v2). The order of the pair is not inportant as edge (v1,v2) is the same as edge (v2,v1).